pandas - 熊猫创建一个具有其他值的新列
问题描述
希望你一切都好,感谢你的时间和帮助。
我的问题是:
我想根据以下条件在数据框中创建一个新列:如果 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"] , 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
解决方案
如果两列中的相同值始终是组中的第一个,则可以使用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
推荐阅读
- linux - 分析在 Kubernetes Linux 中运行的 dotnet 核心进程的内存转储
- kubernetes - Kubernetes Pod 自动伸缩
- solr - Solr fl(字段列表),字段名称中有空格
- javascript - `bind` 不适用于 ReactJS 中的导入函数
- java - 在 Java 8 中使用方法引用时出现编译错误
- android - 如何在@Entity 的 primaryKeys 列表中设置 autoGenerate?
- git - gitlab-ci 中的增量更新
- java - 如何在 CSV 中添加由 Java 中的数据组成的列
- r - R save() 不产生任何输出但没有错误
- php - Laravel 迁移:无法添加外键约束