假设,我们有下一个数据框:
df = pd.DataFrame({'animal': 'cat dog cat fish dog cat cat'.split(),
'size': list('SSMMMLL'),
'weight': [8, 10, 11, 1, 20, 12, 12],
'adult' : [False] * 5 + [True] * 2})
adult animal size weight
0 False cat S 8
1 False dog S 10
2 False cat M 11
3 False fish M 1
4 False dog M 20
5 True cat L 12
6 True cat L 12
我想按权重将其转换为以下形式(非规范化):
weights
animal
cat [8, 11, 12, 12]
dog [10, 20]
fish [1]
目前,我使用以下代码:
df.groupby('animal',as_index=True).apply(lambda sf : pd.Series([list(sf['weight'])]
,index=['weights']))
但我想知道是否有明确的方法可以做到这一点
最佳答案
这只是比你做的方式稍微短一点,但我想你可以做到:
In [22]: df.groupby('animal')['weight'].apply(list)
Out[22]:
animal
cat [8, 11, 12, 12]
dog [10, 20]
fish [1]
Name: weight, dtype: object
或
In [40]: df.groupby('animal')['weight'].apply(list).to_frame()
Out[40]:
weight
animal
cat [8, 11, 12, 12]
dog [10, 20]
fish [1]
第一个输出一个Series
,第二个输出一个DataFrame
。
关于python - Pandas group by 将不同的行转换为具有值数组的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143988/