import pandas as pd
data = [['a',1],['b',2],['c',3]]
df = pd.DataFrame(data, columns = ['letter', 'number']
exclude_list = [2, 4, 6]
我想将df中的第2行(其中“数字” == 2)更改为空/难。我想通过将“数字”列与排除列表进行比较来做到这一点,如果有匹配项,则排除该行。
答案 0 :(得分:4)
检查这些有用的功能:
mask
:让您在满足条件的地方替换值,我们在perform the operation without using no auxiliary data structure (or significant extra storage in simple words)上使用inplace=True
标志。isin
:检查值是否在另一个列表中。
df.number.mask(df.number.isin(exclude_list),inplace=True)
df
Out[200]:
letter number
0 a 1.0
1 b NaN
2 c 3.0
答案 1 :(得分:2)
df.loc[df['number'].isin(exclude_list), 'number'] = None
letter number
0 a 1.0
1 b NaN
2 c 3.0
整行
df.loc[df['number'].isin(exclude_list), :] = None
letter number
0 a 1.0
1 None NaN
2 c 3.0