【问题标题】:Fill null values of a column based on another column condition根据另一列条件填充一列的空值
【发布时间】:2022-01-15 13:10:06
【问题描述】:

我有一个数据集,其中有一列表示受试者的实际年龄,另一列将年龄分类为 10 多岁,即如果受试者是 56 岁,则他们是 50 多岁。下表示例:

age n_age
50s 56
60s 63
10s 17
0s 9
100s 105
20s 25
30s 33
80s 87
90s 92
70s 71
40s 48

我遇到的问题是年龄列有一些空值,我正在尝试根据 Python 中的 n_age 填充它们。

这是我尝试使用的代码

for i in enumerate(df['age']):
    if int(i) == range(0,9):
        df['age'] = df['age'].fillna('0s')
    if int(i) == range(10,19):
        df['age'] = df['age'].fillna('10s')
    if int(i) == range(20,29):
        df['age'] = df['age'].fillna('20s')
    if int(i) == range(30,39):
        df['age'] = df['age'].fillna('30s')
    if int(i) == range(40,49):
        df['age'] = df['age'].fillna('40s')
    if int(i) == range(50,59):
        df['age'] = df['age'].fillna('50s')
    if int(i) == range(60,69):
        df['age'] = df['age'].fillna('60s')
    if int(i) == range(70,79):
        df['age'] = df['age'].fillna('70s')
    if int(i) == range(80,89):
        df['age'] = df['age'].fillna('80s')
    if int(i) == range(90,99):
        df['age'] = df['age'].fillna('90s')
    if int(i) == range(100,109):
        df['age'] = df['age'].fillna('100s')

这不起作用,我不知道它有什么问题,或者我是否应该以另一种方式来做。

提前致谢

【问题讨论】:

标签: python


【解决方案1】:

您可以使用pd.isna 方法创建一个掩码来索引df['age'] 具有NaN 值的行,并使用.loc 直接更改那里的值:

mask = pd.isna(df['age'])
df.loc[mask,'age'] = (df.loc[mask,'n_age'] // 10 *10).astype(str) + 's'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2017-10-12
    相关资源
    最近更新 更多