Pandas 创建一个新列,其中包含来自其他列的值
希望你一切顺利,谢谢你的时间和帮助 我的问题是: 我想基于以下内容在数据帧中创建一个新列: 如果df[“A”]=df[“B”]上的值,则df[“new”]是df[“B”] 大概是这样的:Pandas 创建一个新列,其中包含来自其他列的值,pandas,numpy,dataframe,logic,Pandas,Numpy,Dataframe,Logic,希望你一切顺利,谢谢你的时间和帮助 我的问题是: 我想基于以下内容在数据帧中创建一个新列: 如果df[“A”]=df[“B”]上的值,则df[“new”]是df[“B”] 大概是这样的: A B C 100 100 colors 100 10021 Blue 100 10022 Red . . . 200 200 Shape 200 20021 Square 200 20022 Circle
A B C
100 100 colors
100 10021 Blue
100 10022 Red
.
.
.
200 200 Shape
200 20021 Square
200 20022 Circle
我需要的是一个新列,在df[“a”]==df[“B”],df[“new”]=colors
A B C new
100 100 colors colors
100 10021 Blue colors
100 10022 Red colors
.
.
.
200 200 Shape shape
200 20021 Square shape
200 20022 Circle shape
如果两列中的相同值始终位于组的第一位,则可以使用不相同值的缺失值,然后通过
ffill
将其向前填充:
df['new'] = df['C'].where((df["A"] == df ["B"])).ffill()
print (df)
A B C new
0 100 100 colors colors
1 100 10021 Blue colors
2 100 10022 Red colors
3 200 200 Shape Shape
4 200 20021 Square Shape
5 200 20022 Circle Shape
谢谢你,耶斯雷尔。你救了我