After Pandas Dataframe pd.concat I get NaNs

瘦欲@ 提交于 2019-12-04 14:04:56

问题


I have three pandas df one of them has been 'row'-shifted and the first element is empty. When I concatenate the three df to obtain a single 3-column dataframe I get all NaN in two out of three columns:

df1:

                    S
2010-12-31         True
2011-01-01        False
2011-01-02        False

df2:

               P
2010-12-31           
2011-01-01    On
2011-01-02    On

df3:

              C
2010-12-31    On
2011-01-01    On
2011-01-02    On

res = pd.concat([df1, df2, df3]):

                    P         C           S
2010-12-31        NaN        NaN         True
2011-01-01        NaN        NaN        False
2011-01-02        NaN        NaN        False

The order seems to be inverted as well...

Many thanks


回答1:


In [2]: index = pd.DatetimeIndex(['2010-12-31', '2011-01-01', '2011-01-02'])

In [3]: df1 = pd.DataFrame({'S':[True,False,False]}, index=index)

In [4]: df2 = pd.DataFrame({'P':['','On','On']}, index=index)

In [5]: df3 = pd.DataFrame({'C':['On','On','On']}, index=index)

If your DataFrames are defined as above, then pd.concat with axis=1 should work:

In [7]: pd.concat([df1,df2,df3], axis=1)
Out[7]: 
                S   P   C
2010-12-31   True      On
2011-01-01  False  On  On
2011-01-02  False  On  On

[3 rows x 3 columns]


来源:https://stackoverflow.com/questions/22531164/after-pandas-dataframe-pd-concat-i-get-nans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!