python - 将两列合并为一列

标签 python pandas dataframe merge

如果我有一个数据帧 (df):

Columnx      Columny
1             NA
2             NA
3             NA
NA            4
NA            5
NA            6

想要

Column z
1
2
3
4
5
6

我怎样才能以最简单的方式做到这一点?本质上 x 和 y 是日期列,但由于之前的合并,我有两个日期列,每个都用 NA 填充,另一个被占用,但只需要一个日期列。

最佳答案

使用df.combine_first():

In [58]: df
Out[58]: 
   Column x  Column y
0       1.0       NaN
1       2.0       NaN
2       3.0       NaN
3       NaN       4.0
4       NaN       5.0
5       NaN       6.0

In [59]: df['Column x'].combine_first(df['Column y'])
Out[59]: 
0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
5    6.0
Name: Column_x, dtype: float64

关于python - 将两列合并为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64265275/

相关文章:

python - 在 Pandas 中使用多索引设置值

python - 如何使用 astype() 更改数据框中单列的数据类型?

python - 在 Pandas groupby 操作之后将两列组合成一个集合

python - 在linux和mac中从python查询窗口id

Python 相当于 ignoreboth :erasedups

python - 根据其他列的值在多索引数据框中创建新列的简单方法

r - 解决在数据框列中存储为文本的方程(使用其他列作为输入)

python - Dataframe 将 NA 值转换为 NaN

python - 如果打开现有的 Chrome 窗口,使用默认选项的 Selenium Webdriver 永远不会返回

Python 以逗号分割,不带括号