Python 将数据帧与大量NaN合并

Python 将数据帧与大量NaN合并,python,pandas,Python,Pandas,嗨,我有熊猫数据框,看起来像这样: 0 1 2 3 4 5 6 150 NaN NaN NaN NaN March 1980 NaN NaN 151 NaN NaN NaN NaN June 1990 NaN NaN 152 NaN NaN NaN Sep 2015 N

嗨,我有熊猫数据框,看起来像这样:

      0            1    2         3            4     5     6
150  NaN          NaN  NaN       NaN   March 1980   NaN   NaN
151  NaN          NaN  NaN       NaN    June 1990   NaN   NaN
152  NaN          NaN  NaN  Sep 2015          NaN   NaN   NaN
153  NaN          NaN  NaN  Jan 1972          NaN   NaN   NaN
154  NaN          NaN  NaN  Mar 1974          NaN   NaN   NaN
我不能使用dropna,因为我将有一个空的数据帧

所有列在一列中都有一个数据,有没有办法在一列数据帧中转换它

         0           
150  March 1980
151  June 1990
152  Sep 2015
153  Jan 1972
154  Mar 1974

谢谢。

这就是你想要的吗

df.apply(lambda x : sorted(x,key=pd.isnull),axis=1).dropna(1)
Out[1052]: 
             0
150  March1980
151   June1990
152    Sep2015
153    Jan1972
154    Mar1974

试一试

你得到

150    March 1980
151     June 1990
152      Sep 2015
153      Jan 1972
154      Mar 1974
dtype: object

另一个解决方案是借助布尔掩码和pd.notnull,这比求和和和排序(即

输出:

0 150 March1980 151 June1990 152 Sep2015 153 Jan1972 154 Mar1974
谢谢,它工作得很好,但是.sum1在做什么?我想相信它是对其他列求和,因为它们是空字符串,所以它会折叠为一个?我们在这里使用sum代替join,因为数据类型显然是object。它相当于说df.fillna.apply.join,axis=1bfill非常有趣,但不能再次向上投票@Bharathshetty用我的手机向上投票。。睡觉时间到了。@ShiheZhang的可能复制品不是链接问题的复制品,而是其他问题的复制品。
df = df.fillna('').sum(1)
df = df.fillna('').apply(''.join, axis = 1)
150    March 1980
151     June 1990
152      Sep 2015
153      Jan 1972
154      Mar 1974
dtype: object
sdf = pd.DataFrame(df.values[pd.notnull(df)],index=df.index)
0 150 March1980 151 June1990 152 Sep2015 153 Jan1972 154 Mar1974
ndf = pd.concat([df.reset_index(drop=True)]*1000)

%%timeit
ndf.apply(lambda x : sorted(x,key=pd.isnull),axis=1).dropna(1)
1 loop, best of 3: 1.29 s per loop

%%timeit
ndf.bfill(1).iloc[:,0]
1 loop, best of 3: 773 ms per loop

%%timeit
ndf.fillna('').sum(1)
10 loops, best of 3: 26.4 ms per loop

%%timeit
pd.DataFrame(ndf.values[pd.notnull(ndf)],index=ndf.index)
100 loops, best of 3: 3.11 ms per loop