Issue
I have a data Dataframe like,
data = {
"A": [42, 38, 39,23],
"B": [45, 30, 15,65],
"C": [60, 50, 25,43],
"D": [12, 70, 35,76,],
"E": [87, 90, 45,43],
"F": [40, 48, 55,76],
"G": [58, 42, 85,10],
}
df = pd.DataFrame(data)
print(df)
A B C D E F G
0 42 45 60 12 87 40 58
1 38 30 50 70 90 48 42
2 39 15 25 35 45 55 85
3 23 65 43 76 43 76 10
Here, I need to subtract all the values of columns C to G from column B, then add column A.
Like
df['C']=df['C']-df['B']+df['A']
df['D']=df['D']-df['B']+df['A']
df['E']=df['E']-df['B']+df['A']
How it is possible in simple/single commands?
Solution
You can use a single eval
with a multiline expression:
df = df.eval('''C=C-B+A
D=D-B+A
E=E-B+A
''')
Or, for this particular operation, since all are +A-B:
df[['C', 'D', 'E']] = df[['C', 'D', 'E']].add(df['A'].sub(df['B']), axis=0)
Output:
A B C D E F G
0 42 45 57 9 84 40 58
1 38 30 58 78 98 48 42
2 39 15 49 59 69 55 85
3 23 65 1 34 1 76 10
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.