首页 > 解决方案 > 根据其他列的条件创建新列

问题描述

我有这张表,它显示了小时、总计和 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来实现它吗?

谢谢你。

标签: pythonpandas

解决方案


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

推荐阅读