Deepak M
Deepak M

Reputation: 1224

Converting rows of data which contains a list into NaN values

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

Answers (3)

rafaelc
rafaelc

Reputation: 59274

I would use loc

df.loc[df.C.str.len() > 1, "C"] = np.nan

Upvotes: 1

akilat90
akilat90

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

jezrael
jezrael

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

Related Questions