![](/img/trans.png)
[英]pandas groupby and percentage of occurrences of each value of a column
[英]Pandas groupby with new column for each value
我希望這個標題不言自明; 我只想補充一點,可以假設每個鍵具有相同數量的值。 在線搜索標題產生了以下解決方案:
這應該是解決我的問題,雖然它沒有。 我舉個例子:
輸入:
pd.DataFrame(data={'a':['foo','foo','foo','bar','bar','bar'],'b':[1,2,3,4,5,6]})
輸出:
pd.DataFrame(data={'a':['foo','bar'],'b':[1,4],'c':[2,5],'d':[3,6]})
直觀地說,它將是沒有聚合函數的groupby
函數,或者是從密鑰中生成列表的聚合函數。
顯然,它可以使用for循環等“手動”完成,但是使用具有大數據集的for循環在計算上非常昂貴。
使用GroupBy.cumcount
的Series
或列g
,然后通過重塑DataFrame.set_index
+ Series.unstack
或DataFrame.pivot
,由過去的數據清洗DataFrame.add_prefix
, DataFrame.rename_axis
與DataFrame.reset_index
:
g = df1.groupby('a').cumcount()
df = (df1.set_index(['a', g])['b']
.unstack()
.add_prefix('new_')
.reset_index()
.rename_axis(None, axis=1))
print (df)
a new_0 new_1 new_2
0 bar 4 5 6
1 foo 1 2 3
要么:
df1['g'] = df1.groupby('a').cumcount()
df = df1.pivot('a','g','b').add_prefix('new_').reset_index().rename_axis(None, axis=1)
print (df)
a new_0 new_1 new_2
0 bar 4 5 6
1 foo 1 2 3
如果列名很重要,可以使用groupby.apply
和string.ascii_lowercase
,這是另一種方法:
from string import ascii_lowercase
df = pd.DataFrame(data={'a':['foo','foo','foo','bar','bar','bar'],'b':[1,2,3,4,5,6]})
# Groupby 'a'
g = df.groupby('a')['b'].apply(list)
# Construct new DataFrame from g
new_df = pd.DataFrame(g.values.tolist(), index=g.index).reset_index()
# Fix column names
new_df.columns = [x for x in ascii_lowercase[:new_df.shape[1]]]
print(new_df)
a b c d
0 bar 4 5 6
1 foo 1 2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.