I have a DataFrame and want to get divisions of pairs of columns like below:
df = pd.DataFrame({
'a1': np.random.randint(1, 1000, 1000),
'a2': np.random.randint(1, 1000, 1000),
'b1': np.random.randint(1, 1000, 1000),
'b2': np.random.randint(1, 1000, 1000),
'c1': np.random.randint(1, 1000, 1000),
'c2': np.random.randint(1, 1000, 1000),
})
df['a'] = df['a2'] / df['a1']
df['b'] = df['b2'] / df['b1']
df['c'] = df['c2'] / df['c1']
I want to combine the last three lines into one like:
df[['a', 'b', 'c']] = df[['a2', 'b2', 'c2']] / df[['a1', 'b1', 'c1']]
but I only get an error of ValueError: Columns must be same length as key. If I just simply print(df[['a2', 'b2', 'c2']] / df[['a1', 'b1', 'c1']]), I will only get a DataFrame with NaNs of shape (1000, 6).
==== Edit
Now I know why my original one-line code doesn't work. Actually, the arithmetic operations of two DataFrames will be conducted between the columns with same labels, while those columns without same label in another DataFrame will generate NaNs. The result DataFrame will have the union() of the columns of the two operating DataFrames. That's why my original solution will give an ValueError and the div will generate NaNs.
Following example will be helpful to explain:
df1 = pd.DataFrame(data={'A':[1,2], 'B':[3,4], 'C':[5,6], 'D':[8,9]})
df2 = pd.DataFrame(data={'A':[11,12], 'B':[13,14], 'C':[15,16], 'D':[18,19]})
df1[['A', 'B']] / df2[['A', 'B']]
Out[130]:
A B
0 0.090909 0.230769
1 0.166667 0.285714
df1[['A', 'B']] / df2[['C', 'D']]
Out[131]:
A B C D
0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
df1[['A', 'B']] + df2[['A', 'C']]
Out[132]:
A B C
0 12 NaN NaN
1 14 NaN NaN