[英]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
:这里
isin
和mask
:
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.