【发布时间】:2020-10-01 07:23:03
【问题描述】:
我有一个带有 2 列的 pandas DataFrame:Year(int) 和 Condition(string)。在 Condition 列中,我有一个 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
由于第 6 行中的 nan 值得到 year = 2015 并且从 stat 我得到 2015 年最常见的是“好”,所以我想用“好”值替换这个 nan 值。
我尝试过使用 fillna 和 .transform 方法,但它不起作用:(
如果有任何帮助,我将不胜感激。
【问题讨论】:
标签: python pandas dataframe pandas-groupby fillna