如何为缺失值分组添加NaN

时间:2018-03-02 16:27:36

标签: python pandas

我有一个类似于这个的DataFrame:

import pandas

dd = pandas.DataFrame({'name' : ['foo', 'foo', 'foo', 'bar',
                                 'bar', 'bar', 'bar', 'bar'],
                       'year' : ['1900', '1903', '1904', '1900',
                                 '1901', '1902', '1903', '1904'],
                       'value' : np.arange(8)
                       })

在整个管道中,我需要根据foo的大小来比较barvalue。这就是为什么我想在foo中为缺少的年份添加行,并用NaN填充它们。

所以最后的dd应该有其他行,如下所示:

   value name  year
0    0.0  foo  1900
1    NaN  foo  1901
2    NaN  foo  1902
3    0.1  foo  1903
4    0.2  foo  1904
5    0.3  bar  1900
6    0.4  bar  1901
7    0.5  bar  1902
8    0.6  bar  1903
9    0.7  bar  1904

我尝试使用this solution,但在这种情况下不起作用,因为我在year列中有重复值。

我意识到我必须按'name'添加分组行,但我看不清楚。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

IIUC

dd.set_index(['name','year']).value.unstack().stack(dropna=False).reset_index()
Out[983]: 
  name  year    0
0  bar  1900  3.0
1  bar  1901  4.0
2  bar  1902  5.0
3  bar  1903  6.0
4  bar  1904  7.0
5  foo  1900  0.0
6  foo  1901  NaN
7  foo  1902  NaN
8  foo  1903  1.0
9  foo  1904  2.0