pivot_table 引入的 Pandas NaN

新手上路,请多包涵

我有一张表格,其中包含一些国家及其来自世界银行 API 的 KPI。这看起来像 没有 nan 值 .如您所见,不存在 nan 值。

但是,我需要旋转此表以将 int 转换为正确的形状以供分析。 A pd.pivot_table(countryKPI, index=['germanCName'], columns=['indicator.id']) 对于一些例如 TUERKEI 这工作得很好:

对于土耳其它有效 但是对于大多数国家来说,引入了奇怪的 nan 值。我怎样才能防止这种情况发生?

奇怪的纳米值

原文由 Georg Heiler 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 427
2 个回答

我认为理解 pivoting 的最佳方法是将其应用于小样本:

 import pandas as pd
import numpy as np

countryKPI = pd.DataFrame({'germanCName':['a','a','b','c','c'],
                           'indicator.id':['z','x','z','y','m'],
                           'value':[7,8,9,7,8]})

print (countryKPI)
  germanCName indicator.id  value
0           a            z      7
1           a            x      8
2           b            z      9
3           c            y      7
4           c            m      8

print (pd.pivot_table(countryKPI, index=['germanCName'], columns=['indicator.id']))
             value
indicator.id     m    x    y    z
germanCName
a              NaN  8.0  NaN  7.0
b              NaN  NaN  NaN  9.0
c              8.0  NaN  7.0  NaN

如果需要将 NaN 替换为 0 添加参数 fill_value

 print (countryKPI.pivot_table(index='germanCName',
                              columns='indicator.id',
                              values='value',
                              fill_value=0))
indicator.id  m  x  y  z
germanCName
a             0  8  0  7
b             0  0  0  9
c             8  0  7  0

原文由 jezrael 发布,翻译遵循 CC BY-SA 4.0 许可协议

我会这样做:

 piv_out = pd.pivot_table(countryKPI, index=['germanCName'], columns=['indicator.id'])

print(piv_out.to_string(na_rep=""))

原文由 S2000NOW 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题