简体   繁体   English

在 Pandas DataFrame 中用 NaN 替换字符串(来自列表)

[英]Replacing strings (from a list) with NaN in pandas DataFrame

I have a DataFrame df and a list of strings colnames我有一个 DataFrame df和一个字符串colnames列表

df = pd.DataFrame({'foo': ['a', 'foo', 'c' , 'bar'], 'bar': ['foo', 'b', 'c', 'bar']})

colnames = ['foo', 'bar']

I want to replace the words contained in colnames in my DataFrame df with 'NaN'.我想用“NaN”替换我的 DataFrame df中的colnames中包含的单词。 However, I only want to replace the values and not the column names.但是,我只想替换值而不是列名。 The output should look like:输出应如下所示:

    foo bar
0   a   NaN
1   NaN b
2   c   c
3   NaN NaN

Try this :尝试这个 :

df.replace(colnames, np.nan)

Output :输出

   foo  bar
0    a  NaN
1  NaN    b
2    c    c
3  NaN  NaN

Here isin and mask :这里isinmask

df.mask(df.isin(colnames))

Output:输出:

   foo  bar
0    a  NaN
1  NaN    b
2    c    c
3  NaN  NaN

Let us try replace让我们尝试replace

df.replace(df.columns,np.nan)
   foo  bar
0    a  NaN
1  NaN    b
2    c    c
3  NaN  NaN

You can also use an index mask:您还可以使用索引掩码:

df[~df.isin(colnames)] 

output输出

   foo  bar
0    a  NaN
1  NaN    b
2    c    c
3  NaN  NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM