简体   繁体   中英

Divide slice on slice of the same pandas dataframe

Let's say we have

In [0]: df = pd.DataFrame(data={'col1': [1, 2, 3], 'col2': [3, 4, 5]})
In [1]: df
Out[2]: 
   col1  col2
0     1     3
1     2     4
2     3     5

What I need is to divide df[1:] on df[:-1] and get a dataframe as a result, like this:

Out[3]: 
   col1    col2
0   2.0    1.3333333333333333
1   1.5    1.25

But of course I'm getting

Out[3]: 
   col1  col2
0   NaN   NaN
1   1.0   1.0
2   NaN   NaN

I've tried using iloc for slicing, but got the same result. I'm aware of df.values , but I need a dataframe as a result. Thank you so much.

You can divide numpy array created by values with DataFrame contructor:

df1 = pd.DataFrame(df[1:].values / df[:-1].values, columns=df.columns)
print (df1)
   col1      col2
0   2.0  1.333333
1   1.5  1.250000

Or set same indices in both DataFrames :

df1 = df[1:].reset_index(drop=True).div(df[:-1].reset_index(drop=True))

a = df[1:]
b = df[:-1]
b.index = a.index
df1 = a / b

df2 = df[1:]
df1 = df2.div(df[:-1].set_index(df2.index))

print (df1)
   col1      col2
1   2.0  1.333333
2   1.5  1.250000

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