我正在尝试创建一个新列,该列以另一列中的值为条件,取另一列中值的平均值。
pd.DataFrame({"A":[1, 2, 1, 2],
"B":[4, 6, 8, 12]
我想要创建一个新的列'C‘,将是
pd.DataFrame({"A":[1, 2, 1, 2, 3],
"B":[4, 6, 8, 12, 4],
"C":[6,9,6,9,4]}
如果不清楚,当A列中的值相同时,我希望输出B列中值的平均值。因此,C= (4 +6+.)/n其中A == 1和C= (6 +8+.)/n其中A == 2等等.
我也很难想出这方面的伪代码。任何符合逻辑的解释,除了代码解决方案,都将不胜感激。
发布于 2017-10-21 00:44:52
那是一个transform
In [11]: df
Out[11]:
A B
0 1 4
1 2 6
2 1 8
3 2 12
4 3 4
In [12]: df.groupby("A")["B"].transform('mean')
Out[12]:
0 6
1 9
2 6
3 9
4 4
Name: B, dtype: int64
In [13]: df["C"] = df.groupby("A")["B"].transform('mean')
参见https://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation中的内容。
https://stackoverflow.com/questions/46857099
复制相似问题