我有一個熊貓資料框,其中的列本身包含 np.array。想象一下有這樣的事情:
import random
df = pd.DataFrame(data=[[[random.randint(1,7) for _ in range(10)] for _ in range(5)]], index=["col1"])
df = df.transpose()
這將導致這樣的資料框:
col1
0 [7, 7, 6, 7, 6, 5, 5, 1, 7, 4]
1 [4, 7, 5, 5, 6, 6, 5, 4, 7, 5]
2 [7, 2, 7, 7, 2, 7, 6, 7, 1, 2]
3 [5, 7, 1, 2, 6, 5, 4, 3, 5, 2]
4 [2, 3, 2, 6, 3, 3, 1, 1, 7, 7]
我想將資料框擴展為具有 ["col1",...."col7"] 列的資料框,并計算每一行的出現次數。
所需的結果應該是一個擴展的資料幀,僅包含整數值。
col1 col2 col3 col4 col5 col6 col7
0 1 0 0 1 2 2 4
1 0 0 0 2 3 2 2
2 1 3 0 0 0 1 5
到目前為止,我的方法是相當硬編碼的。我用 0 創建了 col1,...col7 ,之后我使用 iterrows() 來計算出現次數。這很好用,但代碼量很大,我相信有一種更優雅的方法可以做到這一點。也許有 .value_counts() 用于連續每個陣列的東西?
也許有人可以幫我找到它。謝謝
uj5u.com熱心網友回復:
np.random.seed(2022)
from collections import Counter
import numpy as np
df = pd.DataFrame(data=[[[np.random.randint(1,7) for _ in range(10)] for _ in range(5)]],
index=["col1"])
df = df.transpose()
您可以使用Series.explodewithSeriesGroupBy.value_counts和 reshape by Series.unstack:
df1 = (df['col1'].explode()
.groupby(level=0)
.value_counts()
.unstack(fill_value=0)
.add_prefix('col')
.rename_axis(None, axis=1))
print (df1)
col1 col2 col3 col4 col5 col6
0 4 2 1 0 1 2
1 3 2 0 4 0 1
2 3 1 3 2 0 1
3 1 1 3 0 1 4
4 1 1 1 1 3 3
或者將串列推導與Counter和DataFrame建構式一起使用:
df1 = (pd.DataFrame([Counter(x) for x in df['col1']])
.sort_index(axis=1)
.fillna(0)
.astype(int)
.add_prefix('col'))
print (df1)
col1 col2 col3 col4 col5 col6
0 4 2 1 0 1 2
1 3 2 0 4 0 1
2 3 1 3 2 0 1
3 1 1 3 0 1 4
4 1 1 1 1 3 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464385.html
