Python 熊猫:在一个数据帧中合并两列
我有一个pandasPython 熊猫:在一个数据帧中合并两列,python,dataframe,pandas,Python,Dataframe,Pandas,我有一个pandasDataFrame,其中有多个列: 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 dtsta
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)
其中foo
和bar
是包含相同数据但名称不同的列。是否有一种方法可以将构成foo
的行移动到bar
,同时理想地保持bar
的名称
最后,数据帧应显示为:
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)
也就是说,组成条形图的NaN值被foo
中的值替换。请尝试以下操作:
pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)
如果您希望该数据成为新列
bar
,只需将结果分配给df['bar']
您可以直接使用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)
另一个选项是在框架上使用
.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
更现代的pandas版本(至少从0.12开始)具有数据帧和系列对象的方法。例如,如果您的数据帧被称为
df
,您将执行以下操作:
df.bar.combine_first(df.foo)
这只会改变
bar
列的Nan值以匹配foo
列,并且会在原地执行。要用foo
中的值覆盖bar
中的非Nan值,您可以使用update()
方法。您也可以使用numpy
来完成此操作
df['bar']=np.where(pd.isnull(df['bar']),df['foo'],df['bar'])
我没有将concat
视为pandas命名空间中的函数;我不确定我错过了什么。你有什么版本的熊猫?该函数记录在这里:我运行的是pandas版本0.6.1,其中没有包含concat函数。升级到V0.7.3会将concat引入名称空间。工作起来很有魅力!谢谢。谢谢@veenit的捕获,但请注意,由于filldf的索引为0..3,而dflot的索引为1..4,dflot.fillna(filldf)['a'][4]将为nan。不是7.0