0

I have this DataFrame

{'a': {1: 3535226,2: 3776193,3: 3782454, 4: 3206345},
 'b': {1: 1478432,2: 1625943,3: 1617503,4: 1414382},
 'c': {1: 1596643,2: 1841902, 3: 1928081,4: 1648894},
 'a_revenue': {1: 23343.44,2: 28113.64,3: 14166.92,4: 19828.980},
 'b_revenue': {1: 9000.48, 2: 9997.9, 3: 9203.92, 4: 7927.66},
 'c_revenue': {1: 2205.91, 2: 2208.66, 3: 2374.48, 4: 2439.30}}

Is there another way besides my way to divide each revenue column by its column (a_revenue/a and so on)?

I did it this way:

data = [(df.iloc[:,le+3] / df.iloc[:,le])for le in range(len(df.columns)-3)]
columns = [x,y,z]
index = ....
pd.DataFrame(data=data, index=index, column=columns)

It worked but I feel that there must be another way that I just cant figure out.

Thank you!

2 Answers 2

1

Here's a way to do, simply divide the arrays:

newdf = pd.DataFrame(df.iloc[:,3:].values /  df.iloc[:,:3].values, columns = ['x','y','z'])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, did not think about that, much cleaner.
1

Another way is converting df to float and shift backward 3 columns and do division. Slice first 3 columns

df_div = (df.astype(float).shift(-3, axis=1) / df).iloc[:,:3]

Or np.roll

df_div = (np.roll(df, 3, axis=1) / df).iloc[:,:3]

Out[161]:
          a         b         c
1  0.006603  0.006088  0.001382
2  0.007445  0.006149  0.001199
3  0.003745  0.005690  0.001232
4  0.006184  0.005605  0.001479

1 Comment

That is interesting. I will read about shift and understand this way, thanks!

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.