0

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.

4
  • old_df['X'] = old_df['A'] / old_df['B'] Commented Jul 14, 2020 at 12:41
  • I understand how to add these new columns to the existing dataframe, but I want to create a new dataframe for these columns. Commented Jul 14, 2020 at 12:42
  • just declare that variable with new_df = pandas.DataFrame() and then you can new_df['X'] = old_df['A']/old_df['B'] Commented Jul 14, 2020 at 12:44
  • I really thought I tried this already but it's working, thanks. Commented Jul 14, 2020 at 12:49

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.