我想打印Pandas分组的结果。
我有一个数据框架:
import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})
print(df)
A B
0 one 0
1 one 1
2 two 2
3 three 3
4 three 4
5 one 5在按'A‘分组后打印时,我有以下内容:
print(df.groupby('A'))
<pandas.core.groupby.DataFrameGroupBy object at 0x05416E90>如何打印分组的数据帧?
如果我这样做了:
print(df.groupby('A').head())我获取数据帧,就好像它没有被分组一样:
A B
A
one 0 one 0
1 one 1
two 2 two 2
three 3 three 3
4 three 4
one 5 one 5我希望是这样的:
A B
A
one 0 one 0
1 one 1
5 one 5
two 2 two 2
three 3 three 3
4 three 4发布于 2016-04-30 14:59:52
只需执行以下操作:
grouped_df = df.groupby('A')
for key, item in grouped_df:
print(grouped_df.get_group(key), "\n\n")弃用通知:
ix是deprecated in 0.20.0
这也同样有效,
grouped_df = df.groupby('A')
gb = grouped_df.groups
for key, values in gb.iteritems():
print(df.ix[values], "\n\n")用于选择性键分组的:使用gb.keys()在key_list_from_gb中插入所需的键:例如,
gb = grouped_df.groups
gb.keys()
key_list_from_gb = [key1, key2, key3]
for key, values in gb.items():
if key in key_list_from_gb:
print(df.ix[values], "\n")发布于 2017-04-09 23:08:44
如果您只是在寻找一种显示它的方法,您可以使用describe():
grp = df.groupby['colName']
grp.describe()这会给你一张整齐的桌子。
发布于 2020-04-17 13:20:30
除了前面的答案之外:
以你的例子为例,
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})然后是简单的单行代码
df.groupby('A').apply(print)https://stackoverflow.com/questions/22691010
复制相似问题