Pandas pivot_table 引入的 NaN

Pandas NaN introduced by pivot_table

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

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

但是对于大多数国家来说,引入了奇怪的 nan 值。我怎样才能避免这种情况?

我认为理解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

根据文档:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html

pivot 方法returns: 重塑 DataFrame。

现在您可以使用 fillna 方法将 na 值替换为任何所需的值。

例如:

我的枢轴 RETURNS 下面的数据帧:

现在我想用 0 替换 Nan,我将对从 pivot 方法返回的数据框应用 fillna() 方法

我会这样做:

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

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