Reputation: 1224
I have a dataframe like this:
A B C
John 45 [1,0]
Carl 3 [1,2,1]
Fred 4 [-1]
As seen above in column 'C' a few of the rows contain lists. My objective is to convert them to NaN values. I want the output to look like this:
A B C
John 45 NaN
Carl 3 NaN
Fred 4 [-1]
How can I do this?
Upvotes: 0
Views: 87
Reputation: 5696
You can also use:
df['C'][df['C'].apply(len)>1] = np.nan
result:
A B C
0 John 45 NaN
1 Carl 3 NaN
2 Fred 4 [-1]
Upvotes: 1
Reputation: 863166
Use mask
with boolean mask created by len
:
df.C = df.C.mask(df.C.str.len() > 1)
Or:
df.C = np.where(df.C.str.len() > 1, np.nan, df.C)
print (df)
A B C
0 John 45 NaN
1 Carl 3 NaN
2 Fred 4 [-1]
If want convert one item lists to scalars:
df.C = np.where(df.C.str.len() == 1, df.C.str[0], np.nan)
print (df)
A B C
0 John 45 NaN
1 Carl 3 NaN
2 Fred 4 -1.0
Upvotes: 3