python pandas - 将列除以另一列

新手上路,请多包涵

我正在尝试向我的 DataFrame 添加一列,这是其他两列相除的结果,如下所示:

 df['$/hour'] = df['$']/df['hours']

This works fine, but if the value in ['hours'] is less than 1 , then the ['$/hour'] value is greater than the value in ['$'] ,这不是我想要的。

有没有办法控制操作,以便 if ['hours'] < 1 那么 df['$/hour'] = df['$']

原文由 Charon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

您可以使用 numpy.where

 print df
    hours  $
0       0  8
1       0  9
2       0  9
3       3  6
4       6  4
5       3  7
6       5  5
7      10  1
8       9  3
9       3  6
10      5  4
11      5  7

df['$/hour'] = np.where(df['hours'] < 1, df['hours'], df['$']/df['hours'])
print df
    hours  $    $/hour
0       0  8  0.000000
1       0  9  0.000000
2       0  9  0.000000
3       3  6  2.000000
4       6  4  0.666667
5       3  7  2.333333
6       5  5  1.000000
7      10  1  0.100000
8       9  3  0.333333
9       3  6  2.000000
10      5  4  0.800000
11      5  7  1.400000

原文由 jezrael 发布,翻译遵循 CC BY-SA 3.0 许可协议

df['$/hour'] = df.apply(lambda x: x['$'] if x['$'] < 1 else x['$']/x['hours'], axis=1)

原文由 Brian Huey 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题