我有一个索引编号为'l1'的列表,并且我想根据这些索引编号将NaA列中的值替换为
当前数据
Index A
0 Reviewer: Newbie | 35-44 on Treatment for 1
1 Reviewer: 45-54 on Treatment for less than 1
2 Reviewer: Ocetech| 65-74 Male on Treatment
3 Reviewer: virleo| 55-64 Female on Treatment
4 Reviewer: Diane perrin| 65-74 on Treatment for
l1 = [1,3,4]
预期产量
Index A
0 Reviewer: Newbie | 35-44 on Treatment for 1
1 NaN
2 Reviewer: Ocetech| 65-74 Male on Treatment
3 NaN
4 NaN
答案 0 :(得分:1)
使用.loc
在数据帧中的l1中定位索引,然后像这样分配np.nan
:
import numpy as np
df.loc[l1,'A'] = np.nan
答案 1 :(得分:1)
在复制您的DataFrame之后,只需了解细节即可。
也导入numpy,将Nan
的值设置为所需的索引。
import pandas as pd
import numpy as np
您的数据框:
$ df
A
0 Reviewer: Newbie | 35-44 on Treatment for 1
1 Reviewer: 45-54 on Treatment for less than 1
2 Reviewer: Ocetech| 65-74 Male on Treatment
3 Reviewer: virleo| 55-64 Female on Treatment
4 Reviewer: Diane perrin| 65-74 on Treatment for
您的索引列表:
$ l1
[1, 3, 4]
基于loc
对于列A
使用Numpy ..将索引设置为Nan
。
df.loc[l1,'A'] = np.nan
结果:
print(df)
A
0 Reviewer: Newbie | 35-44 on Treatment for 1
1 NaN
2 Reviewer: Ocetech| 65-74 Male on Treatment
3 NaN
4 NaN
请注意,如果您没有一长串要替换为NaN
的索引,则可以直接指定它们,而不用传递列表索引。
$ df.loc[[1,3,4],'A'] = np.nan
$ print(df)
A
0 Reviewer: Newbie | 35-44 on Treatment for 1
1 NaN
2 Reviewer: Ocetech| 65-74 Male on Treatment
3 NaN
4 NaN
$ df.rename(index={1:np.nan, 3:np.nan, 4:np.nan}, inplace=True)