Ján Strompl
Ján Strompl

Reputation: 25

Move columns to the right in Pandas

I have dataset:

Stop_ID On_Demand Tarif Heading
1 T100 Station
2 DYes T101 Gym
3 T101 River

I want to have:

Stop_ID On_Demand Tarif Heading
1 DNo T100 Station
2 DYes T101 Gym
3 DNo T101 River

I tried:

for index, row in sm.iterrows():
    if not row["On_Demand"].startswith("D"):
        sm.loc[index, "Tarif":] = row["On_Demand":]
        sm.loc[index, "On_Demand"] = "DNo"

but it doesnt bring any result. Any idea how can I achieve it?

Upvotes: 1

Views: 913

Answers (1)

jezrael
jezrael

Reputation: 862511

Use DataFrame.shift with axis=1 only filtered rows by inverted mask by ~ and then set column On_Demand by same mask:

m = df["On_Demand"].str.startswith("D")

df.loc[~m, "On_Demand":] = df.loc[~m, "On_Demand":].shift(axis=1)
df.loc[~m, "On_Demand"] = "DNo"

print (df)
   Stop_ID On_Demand Tarif  Heading
0        1       DNo  T100  Station
1        2      DYes  T101      Gym
2        3       DNo  T101    River

Upvotes: 3

Related Questions