1

I am trying to basically look through a column and if that column has a unique value then enter 1 but if it doesn't it just becomes a NaN, my dataframe looks like this:

    Street             Number
0   1312 Oak Avenue     1
1   14212 central Ave   2
2   981 franklin way    1

the code I am using to put the number 1 next to unique values is as follows:

df.loc[(df['Street'].unique()), 'Unique'] = '1'

however when I run this I get this error KeyError: "not in index" I don't know why. I tried running this on the Number column and I get my desired result which is:

    Street            Number    Unique
0   1312 Oak Avenue     1         NaN
1   14212 central Ave   2          1
2   981 franklin way    1          1

so my column that specifies which ones are unique is called Unique and it puts a one by the rows that are unique and NaNs by ones that are duplicates. So in this case I have 2 ones and it notices that and makes the first NaN and the second it provides a 1 and since their is only 1 two then it provides us for a 1 their as well since it is unique. I just don't know why I am getting that error for the street column.

1 Answer 1

1

That's not really producing your desired result. The output of df['Number'].unique(), array([1, 2], dtype=int64), just happened to be in the index. You'd encounter the same issue on that column if Number instead was [3, 4, 3], say.

For what you're looking for, selecting where not duplicated, or where you have left after dropping duplicates, might be better than unique:

df.loc[~(df['Number'].duplicated()), 'Unique'] = 1
df
Out[51]: 
              Street  Number Unique
0    1312 Oak Avenue       1    1.0
1  14212 central Ave       2    1.0
2   981 franklin way       1    NaN


df.loc[df['Number'].drop_duplicates(), 'Unique'] = 1
df
Out[63]: 
              Street  Number  Unique
0    1312 Oak Avenue       1     NaN
1  14212 central Ave       2     1.0
2   981 franklin way       1     1.0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.