reindex排序的pandas数据帧

时间:2016-06-15 23:37:02

标签: python pandas dataframe

我有一个像这样的数据框:

    Column A    Column B    Date       Value
1          A           1   2011-01-01   10
2          B           1   2011-01-01   10
3          A           2   2011-01-01   10
4          B           2   2011-01-01   10
5          A           1   2011-01-02   10
6          B           1   2011-01-02   10
7          A           2   2011-01-02   10
8          B           2   2011-01-02   10
9          A           1   2011-01-03   10
10         B           1   2011-01-03   10
11         B           2   2011-01-03   10

我想找到A和B的每个值的缺失日期(在这种情况下,它将是A,日期:2011-01-03),并在那里插入NaN。我尝试了reindex功能:

df.sort_values(['Column A','Column B'],ascending = [True,True], inplace = True)
df.index = range(1,len(df)+1)
dates = pd.date_range('2011-01-01','2011-01-03')
df = df.reindex(dates, fill_value = None)
print df

但它在每一栏都给了我NaN。有没有人对如何标记这些缺失值有任何建议?

1 个答案:

答案 0 :(得分:3)

试试这个:

df.set_index(['Column A', 'Column B', 'Date']).unstack().stack(dropna=False).sort_index(level=[2, 0]).reset_index()

   Column A  Column B        Date  Value
0         A         1  2011-01-01   10.0
1         B         1  2011-01-01   10.0
2         A         2  2011-01-01   10.0
3         B         2  2011-01-01   10.0
4         A         1  2011-01-02   10.0
5         B         1  2011-01-02   10.0
6         A         2  2011-01-02   10.0
7         B         2  2011-01-02   10.0
8         A         1  2011-01-03   10.0
9         B         1  2011-01-03   10.0
10        A         2  2011-01-03    NaN
11        B         2  2011-01-03   10.0

注意:第10行的缺失值为NaN