我想汇总一个Pandas DataFrame,以便计算每个父亲(变量 father_name )的孩子数量(变量 child_name )。 数据框如下所示(当然,这是一个玩具示例,我想掌握这个概念):
father_name child_name
Robert Julian
Robert Emily
Robert Dan
Carl Jack
Carl Rose
John Lucy
Paul Christopher
Paul Thomas
现在,我定义一个 aggregation 字典并将其用于数据框 d :
import pandas as pd
aggregation = {
'child_name': {
'n_children': 'count'
}
}
d.groupby('father_name').agg(aggregation)
我获得以下输出:
child_name
n_children
father_name
Carl 2
John 1
Paul 2
Robert 3
现在我想:
我该怎么做?也许还有一种更快的方法可以做到这一点,但是我也想学习这种方法。预先感谢!
答案 0 :(得分:2)
你可以让
df_count = df.groupby('father_name').count()
df_count[df_count.child_name > 1].sort_values(by='child_name', ascending=False)
输出:
child_name
father_name
Robert 3
Carl 2
Paul 2
如果您想大量使用agg
,则可能看起来像以下内容(不建议使用dict重命名,而 会抛出FutureWarning
):< / p>
df.groupby('father_name').agg({'child_name': {'n_children': lambda x: len(x) if len(x) > 1 else None}}).dropna()
然后对结果进行排序。
答案 1 :(得分:0)
让我们这样尝试以满足您的两个条件-
import pandas as pd
df = pd.DataFrame({"father_name":["Robert","Robert","Robert","Carl","Carl","John","Paul","Paul"],"child_name":["Julian","Emily","Dan","Jack","Rose","Lucy","Christopher","Thomas"]})
#sort the fathers according to their number of children (in decreasing order)
df = df.groupby(by='father_name').count().sort_values(['child_name'],ascending=False)
#show only the fathers that have 2 or more children
df_greater_2 = df[df['child_name'] >= 2]
print(df_greater_2)