about pandas dataframe reverse column's data order

Viewed 88

Code

import pandas as pd
import numpy as np

df = pd.DataFrame({"K1":[1,2,3],"K2":[4,5,6]})
df["result"] = (df["K1"].shift(1)*df["K2"]).fillna(1)[::-1] #line A
print(df["result"])
print((df["K1"].shift(1)*df["K2"]).fillna(1)[::-1]) #line B
print((df["K1"].shift(1)*df["K2"]).fillna(1)) # line C

Output

0     1.0
1     5.0
2    12.0
Name: result, dtype: float64

2    12.0
1     5.0
0     1.0
dtype: float64

0     1.0
1     5.0
2    12.0
dtype: float64

Why column result not get reverse order in line A but it work in line B?

1 Answers

By using [::-1], you are reversing the Series, including the index (as you can see by your prints). So, the index-value pairs remain the same. Pandas will use the Series index to align the it to the existing index in the df DataFrame. To solve this, you need to assign the raw values to the column, not a Pandas Series, e.g. by using .to_numpy().

df["result"] = (df["K1"].shift(1)*df["K2"]).fillna(1).to_numpy()[::-1] #line A
Related