![](/img/trans.png)
[英]Is there a way to add a new column to a pandas dataframe, appending each unique value of the new column to every existing row of the dataframe?
[英]Pandas add total row at the end of each unique column value
我有一個 dataframe,看起來像:
Item Type Location Count
1 Dog USA 10
2 Dog UK 20
3 Cat JAPAN 30
4 Cat UK 40
5 Bird CHINA 50
6 Bird SPAIN 60
7 Bird UAE 70
我想將總和“計數”列的“總計”行添加到每個唯一“類型”列的末尾,Morover:我只想填寫“類型”列,如下所示:
Item Type Location Count
1 Dog USA 10
2 Dog UK 20
Total Dog 30
3 Cat JAPAN 30
4 Cat UK 40
Total Cat 70
5 Bird CHINA 50
6 Bird SPAIN 60
7 Bird UAE 70
Total Bird 180
我已經嘗試過,它將所有“計數”行值相加:
df.loc["Count"] = df.sum()
首先重置 dataframe 的index
,然后將 dataframe 分組到Type
並使用sum
聚合列Count
並使用max
聚合列,然后分配值為Total
的Item
列。 最后.concat
與原始 dataframe df
的frame
和.sort
索引以保持順序。
frame = df.reset_index()\
.groupby('Type', as_index=False)\
.agg({'Count': 'sum', 'index': 'max'})\
.assign(Item='Total').set_index('index')
pd.concat([df, frame]).sort_index(ignore_index=True)
您可能想嘗試的另一種方法(可能比上述方法更快):
def summarize():
for k, g in df.groupby('Type', sort=False):
yield g.append({'Item': 'Total',
'Type': k, 'Location': '',
'Count': g['Count'].sum()}, ignore_index=True)
pd.concat(summarize(), ignore_index=True)
結果:
Item Type Location Count
0 1 Dog USA 10
1 2 Dog UK 20
2 Total Dog 30
3 3 Cat JAPAN 30
4 4 Cat UK 40
5 Total Cat 70
6 5 Bird CHINA 50
7 6 Bird SPAIN 60
8 7 Bird UAE 70
9 Total Bird 180
df.groupby("Type").agg({"Count": "sum"})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.