0

I have a dataframe with multiple columns

     0    1    2    3
2    1    2    2  155
3    1   92    2  145
4    1   87    2  123
5    1   85    2  146
6    1   79    3  138

I want to crease a new df with the result of deviding col 0/col1, col2/col3...and so on Thanks for the help!

4
  • must the last column be divided by the first one? Commented Feb 11, 2021 at 9:58
  • the first columns [0] has to be devided by the second [1] the third [2] by the forth [3] ...and like that as many columns I have Commented Feb 11, 2021 at 9:59
  • and what about the last one? I mean, the resulting dataframe will have one column less? Commented Feb 11, 2021 at 10:00
  • the resulting dataframe will have half the amount of columns the original dataframe had. because I want the division to take place only on groups of 2 I dont want column [1] to be divided by colum [2], only [0]/[1] , [2]/[3], [4]/[5].... Commented Feb 11, 2021 at 10:08

2 Answers 2

2

You can do something like this:

df1 = df[df.columns[::2]]
df2 = df[df.columns[1::2]]
df2.columns = df1.columns
df1/df2
          0         2
2  0.500000  0.012903
3  0.010870  0.013793
4  0.011494  0.016260
5  0.011765  0.013699
6  0.012658  0.021739
Sign up to request clarification or add additional context in comments.

2 Comments

this will work..now im having issues with the fact that my values seem to be str and not int unsupported operand type(s) for /: 'str' and 'str'. Im trying data=int(df_data) before the lines you wrote but it doesnt seem to do the trick...any suggestion?
@Iva if your dataframe has numeric values only you can do df = df.astype(float)
0
import pandas as pd

#original dataframe
org_df = pd.DataFrame({'0': [1,1,1,1,1], '1':[2,92, 87, 85, 79], '2':[2,2,2,2,2], '3': [155,145,123,146,138]}, index = [2,3,4,5,6])

df = pd.DataFrame()
df['col1'] = org_df['0']/org_df['1']
df['col2'] = org_df['2']/org_df['3']

print(df)

2 Comments

this is an option, however I have hundreds of columns and I wanted to automate it with a loop
You didn't mention it initially

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.