我有一个数据框,看起来像:
>>> df = pd.DataFrame({'id':[1,1,1,1,1,2,2,2],'month':[1,1,2,2,2,1,2,2],'value1':[1,1,3,3,5,6,7,7], 'value2': [9,10,11,12,12,14,15,15], 'others': range(8)})
>>> df
id month value1 value2 others
0 1 1 1 9 0
1 1 1 1 10 1
2 1 2 3 11 2
3 1 2 3 12 3
4 1 2 5 12 4
5 2 1 6 14 5
6 2 2 7 15 6
7 2 2 7 15 7
我想做执行其输入是一系列的自定义功能value1
和value2
:
def get_most_common(srs):
"""
Returns the most common value in a list. For ties, it returns whatever
value collections.Counter.most_common(1) gives.
"""
from collections import Counter
x = list(srs)
my_counter = Counter(x)
most_common_value = my_counter.most_common(1)[0][0]
return most_common_value
预期结果:
value1 value2
id month
1 1 1 9
2 3 12
2 1 6 14
2 7 15
该函数的编写方式是这样的,因为起初我只需要将其应用于value1
如此df = df.groupby(['id,'month'])['value1'].apply(get_most_common)
工作的单个列()。现在,我必须将其同时应用于两列。
尝试次数:
df = df.groupby(['id,'month'])[['value1','value2']].apply(get_most_common)
给:
id month
1 1 value1
2 value1
2 1 value1
2 value1
df = df.groupby(['id,'month'])[['value1','value2']].transform(get_most_common)
给这个
value1 value2
0 1 9
1 1 9
2 3 12
3 3 12
4 3 12
5 6 14
6 7 15
7 7 15
applymap
不起作用。我在这里想念什么?
使用GroupBy.agg
-它分别为每列运行功能:
df = df.groupby(['id','month'])['value1','value2'].agg(get_most_common)
print (df)
value1 value2
id month
1 1 1 9
2 3 12
2 1 6 14
2 7 15
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句