大 pandas :在DataFrame中组合两列 [英] pandas: combine two columns in a DataFrame

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

问题描述

我有一个熊猫 DataFrame ,其中有多个列:

 索引:239897条目,2012-05-11 15:20:00到2012-06-02 23:44:51 
数据列:
foo 11516非空值
bar 228381非空值
Time_UTC 239897非空值
dtstamp 239897非空值
dtypes:float64(4),对象(1)

其中 foo bar 包含相同数据的列名称不同。有没有办法将组成 foo 的行移动到 bar 中,理想情况下保持$ $的名称c $ c> bar ?



最后,DataFrame应该显示为:

 索引: 239897条目,2012-05-11 15:20:00至2012-06-02 23:44:51 
数据列:
bar 239897非空值
Time_UTC 239897非空值
dtstamp 239897非空值
dtypes:float64(4),对象(1)

这是由$ code> foo 中的值替换的组成的NaN值。

解决方案

尝试这样:

  pandas.concat([df ['foo']。 (),df ['bar']。dropna()])。reindex_like(df)

您希望该数据成为新列 bar ,只需将结果分配给 df ['bar'] 。 / p>

I have a pandas DataFrame that has multiple columns in it:

Index: 239897 entries, 2012-05-11 15:20:00 to 2012-06-02 23:44:51
Data columns:
foo                   11516  non-null values
bar                   228381  non-null values
Time_UTC              239897  non-null values
dtstamp               239897  non-null values
dtypes: float64(4), object(1)

where foo and bar are columns which contain the same data yet are named differently. Is there are a way to move the rows which make up foo into bar, ideally whilst maintaining the name of bar?

In the end the DataFrame should appear as:

Index: 239897 entries, 2012-05-11 15:20:00 to 2012-06-02 23:44:51
Data columns:
bar                   239897  non-null values
Time_UTC              239897  non-null values
dtstamp               239897  non-null values
dtypes: float64(4), object(1)

That is the NaN values that made up bar were replaced by the values from foo.

解决方案

Try this:

pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)

If you want that data to become the new column bar, just assign the result to df['bar'].

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

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