[英]Insert into a pandas dataframe slice of another slice from the same dataframe
[英]Divide slice on slice of the same pandas dataframe
假設我們有
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:]
上划分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
進行切片,但是得到了相同的結果。 我知道df.values
,但因此需要一個數據df.values
。 非常感謝。
您可以使用DataFrame
構造values
將values
創建的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
或在兩個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.