原因很简单,您的数据中缺少一对(索引,列)值,例如:
df = pd.DataFrame({"Source": ["foo", "bar", "bar", "bar"],
"Customer Location": ["one", "one", "two", "two", ],
"Total billed £": [10, 20, 30, 40]})
print(df)
设置
Source Customer Location Total billed £
0 foo one 10
1 bar one 20
2 bar two 30
3 bar two 40
如您所见,您的数据中没有 ('foo', 'two') 对,所以当您这样做时:
result = pd.pivot_table(df, index='Source', columns='Customer Location', values='Total billed £')
print(result)
输出
Customer Location one two
Source
bar 20.0 35.0
foo 10.0 NaN
要解决此问题,请使用 fill_value 参数提供默认值:
result = pd.pivot_table(df, index='Source', columns='Customer Location', values='Total billed £', fill_value=0)
输出
Customer Location one two
Source
bar 20 35
foo 10 0