在Pandas中给出以下DataFrame:
import pandas as pd
df = pd.DataFrame(
{
"Date": [
pd.Timestamp("2000-01-02"),
pd.Timestamp("2000-01-02"),
pd.Timestamp("2000-01-05"),
pd.Timestamp("2000-01-06"),
pd.Timestamp("2000-01-06"),
pd.Timestamp("2000-01-06")
],
"Item": ["A", "A", "B", "C", "C", "C"]
}
)
它生成以下DataFrame:
Date Item
0 2000-01-02 A
1 2000-01-02 A
2 2000-01-05 B
3 2000-01-06 C
4 2000-01-06 C
5 2000-01-06 C
如何按日期汇总数据,并将项目作为列标题,如以下格式?
Date A B C
2000-01-02 2 0 0
2000-01-05 0 1 0
2000-01-06 0 0 3
我试
pivot_df = df.pivot_table(index='Date', columns='Item', aggfunc=len, fill_value=0)
但这给了我
Item A B C
Date
2000-01-02 2 0 0
2000-01-05 0 1 0
2000-01-06 0 0 3
我不希望列中的"项目",只是"日期A B C"作为列.