python - 为什么数据透视表中有 NaN?

标签 python pandas dataframe pivot-table

我使用 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/

相关文章:

python - 在 Python 中,如何使函数接受嵌入字符串中的一系列变量?

python - Pycharm 在数据帧连接后不键入提示

python - 将每个 Pandas Dataframe 行绘制为单独的图

将数据框中的某些值替换为 NA

python - pandas 数据帧中缺少季度数据的滞后值和差异

python - 检测 JMESPath 中的匹配失败

Python 列表到位运算

python - OpenCV 错误 : Bad argument (Array should be CvMat or IplImage) file C:\slave\WinInstallerMegaPack\src\opencv\modules\core\src\array. cpp,第 1238 行

python - Matplotlib 填充权重步骤图

r - 排除特定行下方的所有记录