Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

python - pandas equivalent to mutate accros

I would like to perform following operation in Pandas:



library(tidyverse)

df <- tibble(mtcars)

df %>% 
  select(ends_with('t')) %>% 
  head(3)

# Accross all columns that ends with t, add value 100 hundred (+1 for true) if column contains 'at

df %>% 
  mutate(across(ends_with('t'), ~ . + 100 + str_detect(cur_column(), 'at'))) %>% 
  select(ends_with('t') )%>% 
  head(3) %>% view()

Is there any nice equivalent to it? Or at least some really nice one-liner using apply function in pandas?

question from:https://stackoverflow.com/questions/65860419/pandas-equivalent-to-mutate-accros

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try (not sure if this qualifies for you as "nice")

# approach one
cols = [x for x in mtcars.columns if x.endswith("t")]

def f(x, cols):
    for col in cols:
        if "at" in col: 
            x[col] += 101
        else:
            x[col] += 100
    return x
mtcars.apply(f, args=(cols,), axis=1)[cols].head(3)

# approach two 
cols= [col for col in mtcars.columns if col.endswith("t")]
cols_w_at = [col for col in cols if "at" in col]
mtcars[cols] = mtcars[cols].apply(lambda x: x + 100)
mtcars[cols_w_at] = mtcars[cols_w_at].apply(lambda x: x + 1)
mtcars[cols].head(3)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...