简体   繁体   English

在同一熊猫数据帧的切片上划分切片

[英]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: 我需要的是在df[:-1] df[1:]上划分df[1:] df[:-1]并得到一个数据帧,如下所示:

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. 我尝试使用iloc进行切片,但是得到了相同的结果。 I'm aware of df.values , but I need a dataframe as a result. 我知道df.values ,但因此需要一个数据df.values Thank you so much. 非常感谢。

You can divide numpy array created by values with DataFrame contructor: 您可以使用DataFrame构造valuesvalues创建的numpy数组除以:

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 : 或在两个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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