Home > database >  Move columns to the right in Pandas
Move columns to the right in Pandas

Time:02-07

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?

CodePudding user response:

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
  •  Tags:  
  • Related