Is there a way to mimic the pipe operator from R in Python?

Question:

See the example below. Is it possible to put each Python operation on a new line? If I have many operations, the code is not all visible. I need to scroll the VS Code window to the right. Thanks

# R code
data %>%
  group_by(sex) %>%
  summarise(avg_height=mean(height))

# Python code
data.groupby(['sex']).agg(avg_height=('height', 'mean')).reset_index()
Asked By: the_data_guy

||

Answers:

In Python, line breaks inside parentheses are ignored, so you could rewrite as:

(data
    .groupby(['sex'])
    .agg(avg_height=('height', 'mean'))
    .reset_index())

This post may be helpful.

Answered By: the_steve
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.