Reputation: 53
I have a dataframe with columns 'A', 'B', 'C' and I want to create a new dataframe that has columns named 'X', 'Y', 'Z' which will respectively be column 'A' divided by column 'B', 'B' by 'C' and 'A' by 'C'. Also, I want to keep the same index. I have tried the following
new_df = old_df['A'] / old_df['B']
However, I don't know how to add the other columns I want.
Upvotes: 0
Views: 1322
Reputation: 726
You can also use pandas.DataFrame.div which allows you use fill_values. For instance:
new_df = pd.DataFrame(columns=['X','Y','Z'])
new_df['X'] = old_df['A'].div(old_df['B'], fill_value=-9999)
Upvotes: 0
Reputation: 7594
Just do this:
new_df = pd.DataFrame(columns=['X', 'Y', 'Z'])
new_df['X'] = df['A'] / df['B']
new_df['Y'] = df['B'] / df['C']
new_df['Z'] = df['A'] / df['C']
print(new_df)
X Y Z
0 0.227273 0.647059 0.147059
1 1.600000 0.833333 1.333333
2 0.800000 1.666667 1.333333
Upvotes: 3