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.
My sample 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.
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
尝试类似:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.