如何根据多个条件替换NaN值?

时间:2020-10-20 12:39:00

标签: python pandas

我在pandas数据框中有3列。这些是A,B和C列。

data = {"A": [10,12,30,21],
        "B": [12,24,16,31],
        "C": [1,None,None,4]}
df = pd.DataFrame(data, columns = ["A", "B", "C"])
print(df)

我想根据B列中的数据替换C列中的NaN值,例如:

  • 如果B中的值介于10到20之间,我想将C列中的NaN值替换为1,
  • 如果B中的值介于20到30之间,我想将C列中的NaN值替换为2,
  • 如果B中的值介于30到40之间,我想将C列中的NaN值替换为3,

最有效的方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用字典创建replacement_value: index_mask映射,然后对其进行迭代,如下所示:

>>> masks = {1: (df['B'] >= 10) & (df['B'] < 20) & df['C'].isnull(), 2: (df['B'] >= 20) & (df['B'] < 30) & df['C'].isnull(), 3: (df['B'] >= 30) & df['C'].isnull()}
>>> masks
{1: 0    False
1    False
2     True
3    False
dtype: bool, 2: 0    False
1     True
2    False
3    False
dtype: bool, 3: 0    False
1    False
2    False
3    False
dtype: bool}
>>> for replacement_value, mask in masks.items():
...     df.loc[mask, 'C'] = replacement_value
... 
>>> df
    A   B    C
0  10  12  1.0
1  12  24  2.0
2  30  16  1.0
3  21  31  4.0

请注意,我将介于两者之间的条件设为上限,即用1替换df['B']的值必须在[10, 20)]范围内;替换为2 [20, 30)等,因为否则边界会重叠。

答案 1 :(得分:0)

我认为您可以尝试以下方法:

import numpy as np
df['C'].loc[(df['B']<=10) & (df['B']>=1) & (df['C'].isnull())]=1
df['C'].loc[(df['B']<=20) & (df['B']>=11) & (df['C'].isnull())]=2