【问题标题】:Wide to Long data frame returning NaN instead of float values宽到长数据框返回 NaN 而不是浮点值
【发布时间】:2018-10-17 04:29:47
【问题描述】:

我有一个大数据框,如下所示:

     Country    2010         2011        2012         2013
0    Germany    4.625e+10    4.814e+10   4.625e+10    4.593e+10
1    France     6.178e+10    6.460e+10   6.003e+10    6.241e+10
2    Italy      4.625e+10    4.625e+10   4.625e+10    4.625e+10

我想重塑数据,使 Country、Years 和 Values 都是列。我用的是融化法

dftotal = pd.melt(dftotal, id_vars='Country', 
              value_vars=[2010,2011,2012,2013,2014,2015,2016,2016,2017], 
              var_name ='Year', value_name='Total')

我能够达到:

    Country    Year    Total
0   Germany    2010    NaN
1   France     2010    NaN
2   Italy      2010    NaN

我的问题是浮点值变成了 NaN,我不知道如何重塑数据框以将值保持为浮点数。

【问题讨论】:

  • 也许你应该说应该如何填充Total...

标签: python dataframe reshape


【解决方案1】:

省略value_vars 参数,它可以工作:

pd.melt(dftotal, id_vars='Country', var_name ='Year', value_name='Total')

    Country  Year         Total
0   Germany  2010  4.625000e+10
1    France  2010  6.178000e+10
2     Italy  2010  4.625000e+10
3   Germany  2011  4.814000e+10
4    France  2011  6.460000e+10
5     Italy  2011  4.625000e+10
6   Germany  2012  4.625000e+10
7    France  2012  6.003000e+10
8     Italy  2012  4.625000e+10
9   Germany  2013  4.593000e+10
10   France  2013  6.241000e+10
11    Italy  2013  4.625000e+10

问题可能是您的列名不是ints 而是字符串,所以您可以这样做:

dftotal = pd.melt(dftotal, id_vars='Country', 
              value_vars=['2010','2011','2012','2013','2014','2015','2016','2016','2017'], 
              var_name ='Year', value_name='Total')

它也会起作用。

或者,使用stack

dftotal = (dftotal.set_index('Country').stack()
          .reset_index()
          .rename(columns={'level_1':'Year',0:'Total'})
          .sort_values('Year'))

会得到相同的输出(但不太简洁)

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2018-05-11
    • 2015-11-19
    • 1970-01-01
    • 2017-06-09
    • 2013-08-19
    相关资源
    最近更新 更多