All rows in one dataframe substracts another row
Question:
I have a dataframe like this:
ID, A, B, C, D
111 0, 1, 2, 3
222 2, 3, 4, 5
333 3, 4, 5, 6
and a row
A, B, C, D
0, 1, 0, 1
I want every row in the first dataframe minus the row in the above, and do not affect the ID column. The expect result is
ID, A, B, C, D
111 0, 0, 2, 2
222 2, 2, 4, 4
333 3, 3, 5, 5
I don’t know the best way to implement this. Could anyone help? Thanks.
Answers:
You can subsetting df1
from df2
columns to apply subtraction:
df1[df2.columns] = df1[df2.columns] - df2.values
# Or suggested by @mozway
df1[df2.columns] = df1[df2.columns].sub(df2.loc[0], axis=1)
print(df1)
# Output
ID A B C D
0 111 0 0 2 2
1 222 2 2 4 4
2 333 3 3 5 5
Input:
>>> df1
ID A B C D
0 111 0 1 2 3
1 222 2 3 4 5
2 333 3 4 5 6
>>> df2
A B C D
0 0 1 0 1
You can do this:
import pandas as pd
# Create the original DataFrame
df = pd.DataFrame({'ID': [111, 222, 333],
'A': [0, 2, 3],
'B': [1, 3, 4],
'C': [2, 4, 5],
'D': [3, 5, 6]})
# Create the row to subtract from the DataFrame
row = pd.DataFrame({'A': [0], 'B': [1], 'C': [0], 'D': [1]})
# Subtract the row from the DataFrame and update it
df[['A', 'B', 'C', 'D']] = df[['A', 'B', 'C', 'D']] - row.values
# Print the updated DataFrame
print(df)
Result
Id A B C D
0 111 0 0 2 2
1 222 2 2 4 4
2 333 3 3 5 5
I have a dataframe like this:
ID, A, B, C, D
111 0, 1, 2, 3
222 2, 3, 4, 5
333 3, 4, 5, 6
and a row
A, B, C, D
0, 1, 0, 1
I want every row in the first dataframe minus the row in the above, and do not affect the ID column. The expect result is
ID, A, B, C, D
111 0, 0, 2, 2
222 2, 2, 4, 4
333 3, 3, 5, 5
I don’t know the best way to implement this. Could anyone help? Thanks.
You can subsetting df1
from df2
columns to apply subtraction:
df1[df2.columns] = df1[df2.columns] - df2.values
# Or suggested by @mozway
df1[df2.columns] = df1[df2.columns].sub(df2.loc[0], axis=1)
print(df1)
# Output
ID A B C D
0 111 0 0 2 2
1 222 2 2 4 4
2 333 3 3 5 5
Input:
>>> df1
ID A B C D
0 111 0 1 2 3
1 222 2 3 4 5
2 333 3 4 5 6
>>> df2
A B C D
0 0 1 0 1
You can do this:
import pandas as pd
# Create the original DataFrame
df = pd.DataFrame({'ID': [111, 222, 333],
'A': [0, 2, 3],
'B': [1, 3, 4],
'C': [2, 4, 5],
'D': [3, 5, 6]})
# Create the row to subtract from the DataFrame
row = pd.DataFrame({'A': [0], 'B': [1], 'C': [0], 'D': [1]})
# Subtract the row from the DataFrame and update it
df[['A', 'B', 'C', 'D']] = df[['A', 'B', 'C', 'D']] - row.values
# Print the updated DataFrame
print(df)
Result
Id A B C D
0 111 0 0 2 2
1 222 2 2 4 4
2 333 3 3 5 5