如何在Pandas DataFrame中合并/覆盖2列

时间:2019-08-02 17:35:45

标签: python-3.x pandas dataframe

我的数据框中有两列。我想合并/覆盖列。

两列:

Column1 Column2
0   NaT NaT
1   2019-07-17 11:33:22 NaT
2   NaT NaT
3   NaT 2018-05-24 10:00:48

所需结果:

NewColumn
0   NaT
1   2019-07-17 11:33:22
2   NaT
3   2018-05-24 10:00:48

NaT类型:

type(df['Column1'][0])

输出:

pandas._libs.tslibs.nattype.NaTType

日期类型:

type(df['Column1'][1])

输出:

pandas._libs.tslibs.timestamps.Timestamp

1 个答案:

答案 0 :(得分:3)

您可以使用:

fillna()

final=df.assign(New_Col=df.Column1.fillna(df.Column2))

或者:

ffill() iloc[]

final=df.assign(New_Col=df.ffill(1).iloc[:,-1])

              Column1              Column2             New_Col
0                 NaT                  NaT                 NaT
1 2019-07-17 11:33:22                  NaT 2019-07-17 11:33:22
2                 NaT                  NaT                 NaT
3                 NaT  2018-05-24 10:00:48 2018-05-24 10:00:48

用于复制 df的代码:

d=[{'Column1': pd.NaT, 'Column2': 'NaT'},
   {'Column1': pd.Timestamp('2019-07-17 11:33:22'), 'Column2': 'NaT'},
   {'Column1': pd.NaT, 'Column2': pd.NaT},
   {'Column1': pd.NaT, 'Column2': pd.Timestamp('2018-05-24 10:00:48')}]
pd.DataFrame(d)