我希望從型別值創建列標題。然后在新形成的標題下映射適當的 en 值。
資料
country start type en
US 8/1/2022 bb 10
Japan 8/1/2022 aa 25
Japan 9/1/2022 cc 1
期望的
country start aa bb cc
US 8/1/2022 0 10 0
Japan 8/1/2022 25 0 0
Japan 9/1/2022 1 0 0
正在做
# pip install pyjanitor
import pandas as pd
import janitor
df.pivot(
index = 'type',
names_to = ('start', '.value'),
names_pattern = r"(Q\d )_?(. )",
sort_by_appearance = True)
任何建議表示贊賞
uj5u.com熱心網友回復:
嘗試:
df.pivot(index=['country', 'start'], columns='type', values='en').fillna(0, downcast='int').reset_index()
#謝謝,@Sammywemmy。
輸出:
type country start aa bb cc
0 Japan 8/1/2022 25 0 0
1 Japan 9/1/2022 0 0 1
2 US 8/1/2022 0 10 0
或者,
df.groupby(['country', 'start', 'type'])['en'].sum().unstack().fillna(0).astype(int).reset_index()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/526386.html
標籤:Python熊猫麻木的枢
上一篇:Pandas迭代地從字典中添加值
