pandas:在DataFrame中组合两列

BFT*_*FTM 23 python dataframe pandas

我有一个DataFrame包含多个列的pandas :

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)
Run Code Online (Sandbox Code Playgroud)

where foobar是包含相同数据的列,但命名方式不同.是否有移动从而弥补了行的方式foo进入bar,最好同时保持的名字bar

最后,DataFrame应显示为:

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)
Run Code Online (Sandbox Code Playgroud)

这就是组成bar的NaN值被来自的值替换foo.

use*_*737 23

你可以直接使用fillna并将结果分配给列'bar'

df['bar'].fillna(df['foo'], inplace=True)
del df['foo']
Run Code Online (Sandbox Code Playgroud)

一般例子:

import pandas as pd
#creating the table with two missing values
df1 = pd.DataFrame({'a':[1,2],'b':[3,4]}, index = [1,2])
df2 = pd.DataFrame({'b':[5,6]}, index = [3,4])
dftot = pd.concat((df1, df2))
print dftot
#creating the dataframe to fill the missing values
filldf = pd.DataFrame({'a':[7,7,7,7]})

#filling 
print dftot.fillna(filldf)
Run Code Online (Sandbox Code Playgroud)


Bre*_*arn 22

试试这个:

pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)
Run Code Online (Sandbox Code Playgroud)

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


ope*_*onk 5

另一种选择,使用.apply()框架上的方法.您可以根据现有数据重新分配列...

import pandas as pd
import numpy as np

# get your data into a dataframe

# replace content in "bar" with "foo" if "bar" is null
df["bar"] = df.apply(lambda row: row["foo"] if row["bar"] == np.NaN else row["bar"], axis=1) 

# note: change 'np.NaN' with null values you have like an empty string
Run Code Online (Sandbox Code Playgroud)


dag*_*rha 5

更现代的大熊猫版本(因为至少0.12)有combine_first()update()方法数据帧和Series对象.例如,如果调用了您的DataFrame df,您将执行以下操作:

df.bar.combine_first(df.foo)
Run Code Online (Sandbox Code Playgroud)

这只会改变bar列的Nan值以匹配foo列,并且会在原地进行.要覆盖非NaN值在bar与这些foo,你可以使用update()方法.