python - 使用 numpy 和 pandas 如何计算百分比并使用标准并给它负号

标签 python pandas numpy

我有这样的数据:

A   B
25  50
25  25
50  25
75  100
80  100
100 80

我想计算百分比,B 列比 A 高多少%。 所以,% = (B-A)*100,

但是,当 B 小于 A 时,我想显示负号(即 -50%)。因为我只想要 B how many % > A 。

如果 B 小于 A,则它将显示 0 或 - 负号百分比数字。

例如:A=50,B=25,则 (B/A)*100 = -50% 或 0%

enter image description here 有什么想法吗?

最佳答案

您可以使用 Series.masknumpy.where :

df['C'] = (df['B'] / df['A']) * 100
df['D'] = df['C'].mask((df['B'] < df['A']), df['C'] * -1)
print (df)
     A    B           C           D
0   25   50  200.000000  200.000000
1   25   25  100.000000  100.000000
2   50   25   50.000000  -50.000000
3   75  100  133.333333  133.333333
4   80  100  125.000000  125.000000
5  100   80   80.000000  -80.000000
df['C'] = df['B'].div(df['A']).mul(100)
df['D'] = df['C'].mask((df['B'] < df['A']), df['C'].mul(-1))
print (df)
     A    B           C           D
0   25   50  200.000000  200.000000
1   25   25  100.000000  100.000000
2   50   25   50.000000  -50.000000
3   75  100  133.333333  133.333333
4   80  100  125.000000  125.000000
5  100   80   80.000000  -80.000000

df['D'] = np.where((df['B'] < df['A']), df['C'] * -1, df['C'])
print (df)
     A    B           C           D
0   25   50  200.000000  200.000000
1   25   25  100.000000  100.000000
2   50   25   50.000000  -50.000000
3   75  100  133.333333  133.333333
4   80  100  125.000000  125.000000
5  100   80   80.000000  -80.000000

关于python - 使用 numpy 和 pandas 如何计算百分比并使用标准并给它负号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44560716/

相关文章:

python - 如何使用 token 将python包发布到诗歌中的内部 Artifactory

python - 如何在 django 应用程序中访问通过 AJAX 传递的 JSON 数据?

python - 拆分列中的名称

python - 合并不同列上的两个数据框

Python 3.3 无法在 OS X Mavericks 上正常工作

python - Plotly Dash : How to reset the "n_clicks" attribute of a dash-html. 按钮?

python - 在python pandas中获取一个系列的所有元素与之前的元素的区别

python-3.x - 构建新数据框并保留旧数据框?

python - 如何合并两组从 Vivino.com 抓取的信息

python - Numpy 数组集差异