使用 Pandas 将值从一列复制到另一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51039698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:44:18  来源:igfitidea点击:

Copy values from one column to another using Pandas

pythonpandas

提问by Yiyi

I have a DataFrame with two columns X and Y:

我有一个包含两列 X 和 Y 的 DataFrame:

   X      Y
0  0  111.0
1  3    NaN
2  1    NaN
3  1  112.0
4  2  113.0
5  2    NaN
6  3  114.0
7  3  115.0
8  1    NaN
9  2  116.0

I want to copy in Y only the values of X that correspond to the rows where a NaN is. The expected result should look like this

我只想在 Y 中复制与 NaN 所在行对应的 X 值。预期的结果应该是这样的

   X    Y
0  0  111
1  3    3
2  1    1
3  1  112
4  2  113
5  2    2
6  3  114
7  3  115
8  1    1
9  2  116

Is there any way to achieve this?

有没有办法实现这一目标?

回答by Sreeram TP

You can simply use the fillna()function available in pandas to solve this very efficiently.

您可以简单地使用fillna()pandas 中可用的函数来非常有效地解决这个问题。

Below code explains how to it in Python.

下面的代码解释了如何在 Python 中使用它。

df = pd.DataFrame()

df['X'] = [0, 3, 1, 1, 2, 2, 3, 3, 1, 2]
df['Y'] = [111.0, np.nan, np.nan, 112, 113, np.nan, 114, 115, np.nan, 116]

df['Y'] = df['Y'].fillna(df['X'])

print(df)

回答by Rakesh

Use df["Y"].fillna(df["X"])

df["Y"].fillna(df["X"])

Ex:

前任:

import pandas as pd
import numpy as np
df = pd.DataFrame({"X": [3, 4, 5, 6], "Y": [10, np.nan, 7, np.nan]})
df["Y"] = df["Y"].fillna(df["X"])
print(df)

Output:

输出:

   X     Y
0  3  10.0
1  4   4.0
2  5   7.0
3  6   6.0

回答by Allan J

Here one liner:

这里有一个班轮:

df.loc[df['Y'].isnull(), 'Y'] = df['X']

回答by U10-Forward

Another way:

其它的办法:

df['Y'] = [row[-2] if row[-1]=='Nan' else row[-1] for row in df.itertuples()]
print(df)

Output:

输出:

   X    Y
0  0  111
1  3    3
2  1    1
3  1  112
4  2  113
5  2    2
6  3  114
7  3  115
8  1    1
9  2  116