我有一個資料集 df,我想將列名與每個列值組合起來并顯示標簽計數。
For example, for id 'aa' in 2022 Q1, there is 1 'hi'
for id 'aa' in 2022 Q2, there are 2 'hi' 's
資料
id type date Q1 Q2
aa hi 2022 1 2
aa hi 2023 1 1
aa ok 2022 1 0
bb hi 2024 3 0
想要的
id type date count
aa hi Q1 2022 hi01
aa ok Q1 2022 ok01
aa hi Q2 2022 hi01
aa hi Q2 2022 hi02
aa hi Q1 2023 hi01
aa hi Q2 2023 hi01
bb hi Q1 2024 hi01
bb hi Q1 2024 hi02
bb hi Q1 2024 hi03
正在做
我的方法是分步分解。我相信我必須執行一個支點,加入和計算:
#創建一個支點
df.set_index(['id', 'type']).stack().reset_index()
#設定計數
df['count'] = df['type'] df.groupby([*df]).cumcount().add(1).astype(str).str.zfill(2)
任何建議表示贊賞
uj5u.com熱心網友回復:
您可以使用以下內容:
(df.melt(id_vars=['id', 'type', 'date'], value_name='count') # reshape data
.sort_values(by=['date', 'variable'])
# duplicate the rows according to counts
.loc[lambda d: d.index.repeat(d['count'])]
.reset_index(drop=True)
# merge the quarters and years
.assign(date=lambda d: d['variable'] ' ' d['date'].astype(str),
# increment the type per group
count=lambda d: d['type'] d.groupby(['id', 'date', 'type']).cumcount().add(1).astype(str).str.zfill(2)
)
# drop now unused column
.drop(columns='variable')
)
輸出:
id type date count
0 aa hi Q1 2022 hi01
1 aa ok Q1 2022 ok01
2 aa hi Q2 2022 hi01
3 aa hi Q2 2022 hi02
4 aa hi Q1 2023 hi01
5 aa hi Q2 2023 hi01
6 bb hi Q1 2024 hi01
7 bb hi Q1 2024 hi02
8 bb hi Q1 2024 hi03
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362000.html
