简体   繁体   中英

Efficiently relocate elements conditionally in a panda.Dataframe

I am trying to sort the values of my data.frame in the following way:

for i in range(len(df.index)):
    if df.at[i, "x1"] <= df.at[i, "x2"]:
        df2.at[i, "p1"] = df.at[i, "p1"]
        df2.at[i, "x1"] = df.at[i, "x1"]
        df2.at[i, "x2"] = df.at[i, "x2"]
    else:
        df2.at[i, "p1"] = df.at[i, "p2"]
        df2.at[i, "x1"] = df.at[i, "x2"]
        df2.at[i, "x2"] = df.at[i, "x1"]

It is working, however it is very slow for my +40k rows. How can I do this more efficiently and more elegantly? I would prefer a solution that directly manipulates the original df, if possible.

Example data:

x1  p1 x2   p2
1  0.4  2  0.6
2  0.2  1  0.8

Desired output:

x1  p1 x2   p2
1  0.4  2  0.6
1  0.8  2  0.2

Here's one way that use a selection of the rows and then does a swap of the values using that selection

check = df["x1"] > df["x2"]
df.loc[check, ["x2", "x1", "p2", "p1"]] = df.loc[check, ["x1", "x2", "p1", "p2"]].values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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