首页 > 解决方案 > 熊猫创建一个具有其他值的新列

问题描述

希望你一切都好,感谢你的时间和帮助。

我的问题是:

我想根据以下条件在数据框中创建一个新列:如果 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

我需要的是一个新列,而在 df["A"] == df["B"] , d​​f["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

标签: pandasnumpydataframelogic

解决方案


如果两列中的相同值始终是组中的第一个,则可以使用Series.where不同值的缺失值,然后通过以下方式向前填充它们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

推荐阅读