我有一个带有2列的Pandas DataFrame:Year(int)和Condition(string)。在“条件”列中,我有一个nan值,我想根据来自groupby操作的信息来替换它。
import pandas as pd
import numpy as np
year = [2015, 2016, 2017, 2016, 2016, 2017, 2015, 2016, 2015, 2015]
cond = ["good", "good", "excellent", "good", 'excellent','excellent', np.nan, 'good','excellent', 'good']
X = pd.DataFrame({'year': year, 'condition': cond})
stat = X.groupby('year')['condition'].value_counts()
它给出:
print(X)
year condition
0 2015 good
1 2016 good
2 2017 excellent
3 2016 good
4 2016 excellent
5 2017 excellent
6 2015 NaN
7 2016 good
8 2015 excellent
9 2015 good
print(stat)
year condition
2015 good 2
excellent 1
2016 good 3
excellent 1
2017 excellent 2
由于第六行的nan值表示year = 2015,而从统计数据中我得到的是从2015年开始,最经常出现的是“好”,所以我想用“ good”值代替这个nan值。
我已经尝试过fillna和.transform方法,但是它不起作用:(
我将不胜感激。
答案 0 :(得分:1)
我做了一些额外的转换,使stat
作为字典将年份映射到其最高频率名称(贷记为this answer):
In[0]:
fill_dict = stat.unstack().idxmax(axis=1).to_dict()
fill_dict
Out[0]:
{2015: 'good', 2016: 'good', 2017: 'excellent'}
然后根据此字典将fillna
与map
一起使用(贷记this answer):
In[0]:
X['condition'] = X['condition'].fillna(X['year'].map(fill_dict))
X
Out[0]:
year condition
0 2015 good
1 2016 good
2 2017 excellent
3 2016 good
4 2016 excellent
5 2017 excellent
6 2015 good
7 2016 good
8 2015 excellent
9 2015 good