python - 根据其他列的条件创建新列
问题描述
我有这张表,它显示了小时、总计和 km_length:
type hour km_length total
A 1 1
B 2 1
我想添加显示费率的列。费率可以通过两列计算,有两种情况:
(1) rate = (hour x 100) / total
(2) rate = (km_length x 1000000) / total
当该行具有小时值时,它将使用第一个等式。如果该行在 km_length 上有值,那么它将使用第二个等式。
那么表格将是这样的:
type hour km_length total rate
A 1 1 100
B 2 1 2000000
无论如何我可以通过使用python来实现它吗?
谢谢你。
解决方案
pandas.DataFrame.bfill
与 一起使用axis==1
:
# df = df.replace("", np.nan) # In case it's whitespace(s) instead of np.nan
df["hour"] = df["hour"] * 100
df["km_length"] = df["km_length"] * 1000000
df["rate"] = df.bfill(1)["hour"]/df["total"]
print(df)
输出:
type hour km_length total rate
0 A 100.0 NaN 1 100
1 B NaN 2000000.0 1 2e+06
推荐阅读
- android-studio - 在 TeamCity 上通过 gradle build step 构建 android 项目时如何修复“Aapt2InternalException:AAPT2”错误?
- chef-infra - 通过配置定义 Chef Kitchen 实例的自定义结构?
- android - 将像素从一种密度转换为另一种
- java - Junit 测试断言错误预期为 3,但附带 0
- node-modules - 错误:使用离子服务时缺少绑定
- php - strtotime PHP的奇怪响应
- sparql - 基本 SPARQL 查询返回三元组,其标签包含 Blazegraph 中的字符串
- rpm - 在 spec 中指定命令卸载 RPM 包
- python - Why is my if statement producing a key error?
- elasticsearch - 在弹性搜索中向现有映射添加默认值