Pandas将df.count()结果的最后n行求和为一行

tgabmvqs  于 2023-01-24  发布在  其他
关注(0)|答案(3)|浏览(186)

我正在寻找一种方法来生成一个 Dataframe 的汇总统计信息。考虑以下示例:

>> df = pd.DataFrame({"category":['u','v','w','u','y','z','y','z','x','x','y','z','x','z','x']})

>> df['category'].value_counts()
z    4
x    4
y    3
u    2
v    1
w    1

>> ??
           count  pct
z              4  27%
x              4  27%
y              3  20%
Other (3)      4  27%

结果是对最后n=3行的值计数求和,删除它们,然后将它们作为一行添加到原始值计数中。另外,将所有值都表示为百分比也很好。有什么想法如何实现这个吗?干杯!

djp7away

djp7away1#

对于带有百分比的DataFrame,使用带有索引的Series.iloc,按Series.to_frame创建DataFrame,添加用百分比填充的新行和新列:

s = df['category'].value_counts()

n= 3
out = s.iloc[:-n].to_frame('count')
out.loc['Other ({n})'] = s.iloc[-n:].sum()
out['pct'] = out['count'].div(out['count'].sum()).apply(lambda x: f"{x:.0%}")
print (out)
           count  pct
z              4  27%
x              4  27%
y              3  20%
Other (3)      4  27%
jogvjijk

jogvjijk2#

我将使用tail(-3)来获取除前3个值之外的最后几个值:

counts = df['category'].value_counts()
others = counts.tail(-3)

counts[f'Others ({len(others)})'] = others.sum()
counts.drop(others.index, inplace=True)

counts.to_frame(name='count').assign(pct=lambda d: d['count'].div(d['count'].sum()).mul(100).round())

输出:

count   pct
z               4  27.0
x               4  27.0
y               3  20.0
Others (3)      4  27.0
cyvaqqii

cyvaqqii3#

此片段

df = pd.DataFrame({"category":['u','v','w','u','y','z','y','z','x','x','y','z','x','z','x']})
cutoff_index = 3
categegory_counts = pd.DataFrame([df['category'].value_counts(),df['category'].value_counts(normalize=True)],index=["Count","Percent"]).T.reset_index()
other_rows = categegory_counts[cutoff_index:].set_index("index")
categegory_counts = categegory_counts[:cutoff_index].set_index("index")
summary_table = pd.concat([categegory_counts,pd.DataFrame(other_rows.sum(),columns=[f"Other ({len(other_rows)})"]).T])
summary_table = summary_table.astype({'Count':'int'})
summary_table['Percent'] = summary_table['Percent'].apply(lambda x: "{0:.2f}%".format(x*100))
print(summary_table)

会给予你你所需要的。也是在一个很好的格式;)

Count Percent
z              4  26.67%
x              4  26.67%
y              3  20.00%
Other (3)      4  26.67%

相关问题