[英]Compare two columns with conditions
I have two column, say A and B. I want to compare if A exceeds column B more than 500, add 1 in new column, else 0.我有两列,比如 A 和 B。我想比较 A 是否超过 B 列超过 500,在新列中添加 1,否则为 0。
My sample df:我的示例 df:
A B
13450 12000
10000 12000
5240 5000
5000 5000
60000 70000
Expected result:预期结果:
A B C
13450 12000 1
10000 12000 0
5600 5000 1
5000 5000 0
60000 70000 0
Using the 'Greater Than' I can compare two column, but I can't figure out how to do this for a condition A column exceeds B more than 500.使用“大于”我可以比较两列,但我无法弄清楚如何在条件 A 列超过 B 超过 500 的情况下执行此操作。
Any help would be much appreciated!任何帮助将非常感激!
>>> df['C'] = (df.A - df.B).ge(500).astype(int)
>>> df
A B C
0 13450 12000 1
1 10000 12000 0
2 5240 5000 0
3 5000 5000 0
4 60000 70000 0
You can find the difference of the column using the -
operator, then check condition is greater than 500
using pandas.Series.ge
method and finally convert it into int
type by pandas.Series.astype
您可以使用
-
运算符找到列的差异,然后使用pandas.Series.ge
方法检查条件是否大于500
,最后通过pandas.Series.astype
将其转换为int
类型
尝试类似:
df['c'] = np.where((( df['a']-df['b']) > 500), 1,0)
It is a very simple logic just some basic comparing operation to be performed这是一个非常简单的逻辑,只是要执行一些基本的比较操作
import pandas as pd
df = pd.read_excel('pathoffile.xlsm')
a = df['col1'].tolist()
b = df['col2'].tolist()
c=[]
for i in len(a):
if a[i]-b[i]<500:
c.append(0)
else:
c.append(1)
print(c)
Now write the c value into the xls file in third coloum into the xls file and you will get the desired result.现在将 c 值写入到 xls 文件中的第三个 coloum 中的 xls 文件中,您将获得所需的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.