Pandas相当于突变的阿克罗斯

2024-06-02 13:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在熊猫中执行以下操作:



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()

有什么与之相当的好东西吗?或者至少有一些非常好的单行程序在pandas中使用apply函数


Tags: columnsdfthatwithlibrarycolumnallselect
2条回答

你可以试试(不确定这是否适合你)

# 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)

您可以将字典理解解压为^{}的关键字参数(assign类似于dplyr::mutate

import pandas as pd
from statsmodels.datasets import get_rdataset

mtcars = get_rdataset('mtcars').data

(mtcars
 .assign(**{col: mtcars[col].add(100).add('at' in col) 
            for col in mtcars.filter(regex='t$')})
.filter(regex='t$')
.head(3)
)

输出:

                 drat       wt
Mazda RX4      104.90  102.620
Mazda RX4 Wag  104.90  102.875
Datsun 710     104.85  102.320

相关问题 更多 >