简体   繁体   中英

Dividing multiple columns in a python dataframe with each other

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!

这是一种方法,只需将数组分开:

newdf = pd.DataFrame(df.iloc[:,3:].values /  df.iloc[:,:3].values, columns = ['x','y','z'])

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM