在相同的pandas数据帧的切片上划分切片

时间:2018-03-26 07:37:35

标签: python pandas

假设我们有

http://10.1.15/data/settings.json

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

df[:-1]

但我当然得到了

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

我尝试使用Out[3]: col1 col2 0 NaN NaN 1 1.0 1.0 2 NaN NaN 进行切片,但结果相同。我知道iloc,但我需要一个数据帧。非常感谢你。

1 个答案:

答案 0 :(得分:2)

您可以将values创建的numpy数组与DataFrame构造函数分开:

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

或者在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