pandas:在DataFrame中组合两列

时间:2012-06-10 21:12:43

标签: python dataframe pandas

我有一个pandas DataFrame,里面有多个列:

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)

其中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)

这就是组成bar的NaN值被foo的值替换。

5 个答案:

答案 0 :(得分:23)

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

df['bar'].fillna(df['foo'], inplace=True)
del df['foo']

一般例子:

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)

答案 1 :(得分:22)

试试这个:

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

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

答案 2 :(得分: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

答案 3 :(得分:5)

更现代的pandas版本(至少0.12)具有DataFrame和Series对象的combine_first() and update()方法。例如,如果您的DataFrame名为df,则可以执行以下操作:

df.bar.combine_first(df.foo)

只会改变bar列的Nan值以匹配foo列,并且会在原地进行。要使bar中的非Nan值覆盖foo中的非Nan值,您可以使用update()方法。

答案 4 :(得分:2)

您也可以使用numpy执行此操作。

df['bar'] = np.where(pd.isnull(df['bar']),df['foo'],df['bar'])

相关问题