Victor De Simone
Victor De Simone

Reputation: 33

Pythonic way of writing a long line of code

count_lbl = pd.DataFrame(labels_dataframe.sum(axis=1) \
    .sort_values(ascending=False)) \
    .reset_index() \
    .groupby(0).count() \
    .reset_index() \
    .rename(columns={0:'num_lbl','index':'count'})

I am fairly new to Python and i would like to know if this is the best way of writing a long line of code, with multiple sequenced actions on an object.

Upvotes: 2

Views: 158

Answers (2)

RayLuo
RayLuo

Reputation: 19230

The other answer's approach is to use an extra pair of parentheses. That's fine.

There is also an alternative that just reorganize the lines to take advantage of existing parentheses.

count_lbl = pd.DataFrame(
        labels_dataframe.sum(axis=1).sort_values(ascending=False)
    ).reset_index().groupby(0).count().reset_index().rename(
        columns={0:'num_lbl','index':'count'}
    )

In particular:

  • Indentation is organized to represent the logical scope, this would address the suggestion mentioned by @Rory-Browne in his comment.
  • Line 2 is not currently further split into each function call. But you can easily do that, because they are within a pair of natural parentheses.
  • Line 3 does not currently further split each function call. If you really want to, you can bring back that extra outer parenthesis, so that line 3 can be split into smaller snippets. But I think its current form here is good enough, because:

Upvotes: 2

Jason Yang
Jason Yang

Reputation: 13061

You can use left and right parentheses

count_lbl = (pd.DataFrame(labels_dataframe.sum(axis=1)
    .sort_values(ascending=False))
    .reset_index()
    .groupby(0).count()
    .reset_index()
    .rename(columns={0:'num_lbl','index':'count'}))

Upvotes: 5

Related Questions