组合数据框的列 [英] Combining columns of dataframe

查看:53
本文介绍了组合数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据框:

   c1   c2   c3
0   a   NaN  NaN
1  NaN   b   NaN
2  NaN  NaN   c
3  NaN   b   NaN
4   a   NaN  NaN

我想像这样组合这三列:

I want to combine these three columns like this :

    c4
0    a
1    b
2    c
3    b
4    a

下面是制作上述数据框的代码:

a = pd.DataFrame({
    'c1': ['a',np.NaN,np.NaN,np.NaN,'a'],
    'c2': [np.NaN,'b',np.NaN,'b',np.NaN],
    'c3': [np.NaN,np.NaN,'c',np.NaN,np.NaN]
})

推荐答案

bfilling 是一种选择:

a.bfill(axis=1).iloc[:,0]

0    a
1    b
2    c
3    b
4    a
Name: c1, dtype: object


另一个是简单的堆栈,去掉 NaN.


Another one is a simple stack, gets rid of NaNs.

a.stack().reset_index(level=1, drop=True) 


0    a
1    b
2    c
3    b
4    a
dtype: object


您每天都不会看到的另一个有趣的选择是使用 NumPy 的强大功能.这是Divakar 的justify 实用程序 的修改版本,适用于对象数据帧.


Another interesting option you don't see everyday is using the power of NumPy. Here's a modified version of Divakar's justify utility that works with object DataFrames.

justify(a.to_numpy(), invalid_val=np.nan)[:,0]
# array(['a', 'b', 'c', 'b', 'a'], dtype=object)

# as a Series
pd.Series(justify(a.to_numpy(), invalid_val=np.nan)[:,0], index=a.index)

0    a
1    b
2    c
3    b
4    a
dtype: object

这篇关于组合数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆