Fillna() 取决于另一列

时间:2021-03-03 15:01:54

标签: pandas fillna

接下来我想做: 根据 DF1 中的列值,用来自 DF2 的值填充 DF1 NaN。

基本上,DF1 中包含“income_type”和“total_income”中的一些 NaN。在 DF2 中,每个“收入类型”都有“收入中位数”。我想用 DF2 的中值填充“total_income”DF1 中的 NaN DF1DF2

2 个答案:

答案 0 :(得分:0)

首先,我将通过“收入类型”将 DF2 中的值合并到 DF1

DF3 = DF1.merge(DF2, how='left', on='income_type')

通过这种方式,您可以在同一数据框中获得收入中位数和总收入的值。 在此之后,我将对熊猫数据框列执行 if else 语句

DF3.loc[DF3['total_income'].isna(), 'total_income'] = DF3['median income']

这会将 NaN 值替换为合并中的中值

答案 1 :(得分:0)

您需要加入两个数据框,然后用中位数替换 nan 值。这是一个类似的工作示例。干杯伙计。

import pandas as pd

#create the example dataframes
df1 = pd.DataFrame({'income_type':['a','b','c','a','a','b','b'], 'total_income':[200, 300, 500,None,400,None,None]})
df2 = pd.DataFrame({'income_type':['a','b','c'], 'median_income':[205, 305, 505]})

# inner join the df1 with df2 on the column 'income_type'
joined = df1.merge(df2, on='income_type')

# fill the nan values the value from the column 'median_income' and save it in a new column 'total_income_not_na'
joined['total_income_not_na'] = joined['total_income'].fillna(joined['median_income'])
print(joined)
相关问题