Home > Net >  Is there a way to shorten dataframe name references?
Is there a way to shorten dataframe name references?

Time:07-04

When working with Pandas dataframes, I often run into long chains of operations. Like this:

df_movement["speed"] = df_movement["distance"] / df_movement["time"]
df_movement["estimated_time"] = df_movement["target_distance"] / df_movement["speed"]

And so on. I have to keep writing df_movement[whatever] dozens of times.

Is there a way to shorten this, so I don't have to keep writing the "df_movement" part over and over again? Some way to use a with statement on a dataframe?

CodePudding user response:

I wouldn't say that it's much better to read or shorter to write, but if you prefer you can do the same in just one call to assign, especially if you have a lot of new columns to create:

df_movement = df_movement.assign(speed = lambda x: x.distance/x.time,
                                 estimated_time = lambda x: x.target_distance/x.speed)
  • Related