我使用 df = df.fillna(0)
从 df 中删除了所有 NaN。
在我使用
创建数据透视表之后pd.pivot_table(df, index='Source', columns='Customer Location', values='Total billed £')
我仍然再次得到 NaN
数据作为输出。
有人可以向我解释为什么以及如何阻止此输出以及为什么会发生这种情况吗?
最佳答案
由于您的输入数据,它将一列转换为索引,将另一列的值转换为列。这些的交集是聚合值。
但如果输入数据中不存在某些组合,则会导致数据丢失 (NaN
)。
df = pd.DataFrame({
'Source':list('abcdef'),
'Total billed £':[5,3,6,9,2,4],
'Customer Location':list('adfbbb')
})
print (df)
Source Total billed £ Customer Location
0 a 5 a
1 b 3 d
2 c 6 f
3 d 9 b
4 e 2 b
5 f 4 b
#e.g because `Source=a` and `Customer Location=b` not exist in source then NaN in output
print (pd.pivot_table(df,index='Source', columns='Customer Location',values='Total billed £'))
Customer Location a b d f
Source
a 5.0 NaN NaN NaN
b NaN NaN 3.0 NaN
c NaN NaN NaN 6.0
d NaN 9.0 NaN NaN
e NaN 2.0 NaN NaN
f NaN 4.0 NaN NaN
此外,here's一本关于 reshape 数据
的好书。
关于python - 为什么数据透视表中有 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624536/