pythonpython-3.xpandas

Breaking long method chains into multiple lines in Python


I'm learning Python and pandas and I very often end up with long chains of method calls. I know how to break lists and chains of operators in a way that compiles, but I can't find a way to break method chains in a way that doesn't feel like cheating.

There's plenty of examples of breaking up operator chains and lists in the googles, but I can't find anything decent for method chains.

What would be the best way in Python 3 to break a long chain of method calls into multiple lines?

Say a line like this one:

t_values = df_grouped_by_day.sort_values('day_of_week').groupby(['day_of_week', 'day_of_week_name'])['Show_up'].apply(lambda sample: ttest_ind(population, sample)).reset_index()

Solution

  • Best approach I've came up with so far is this:

    t_values = (df_grouped_by_day
               .sort_values('day_of_week')
               .groupby(['day_of_week', 'day_of_week_name'])['Show_up']
               .apply(lambda sample: ttest_ind(population, sample))
               .reset_index())