Home > Mobile >  How do I swap values in a column in python
How do I swap values in a column in python

Time:09-20

photo of my dataframe

Hi, how can I switch every two values in a column with each other? What happened is the bowler pca values somehow got swapped in this dataframe, so I need to switch them around for all the games. ie Karachi Kings should have a bowler pca of -0.752828 and Quetta Gladiators should have the pca of -0.216844. I need to do this for every game, but I have no clue how to tackle this at all. Could someone help me out?

CodePudding user response:

You could combine two lists (even and odds of the DataFrame column) to switch the values around:

df["bowler_PCA"] = [z for x, y in zip(df["bowler_PCA"].iloc[1::2], df["bowler_PCA"].iloc[::2]) for z in [x, y]]

CodePudding user response:

This one here seems to work:

data = pd.DataFrame({"matchId": [1, 1, 2, 2], "bowler_PCA": [-1, 1, -2, 2]})


data["bowler_PCA"] = data.groupby("matchId")["bowler_PCA"].transform(lambda x: x.iloc[::-1].values)

With output

   a  b
0  1  1
1  1 -1
2  2  2
3  2 -2
  • Related