python - 有没有一种优雅的方法可以在Python中调用同一对象的方法列表?

标签 python python-3.x pandas

我想知道是否有一种优雅的或更简单的方法来调用 python 中同一对象的方法列表,而不是每次都重复编写。例如:

df['date_col'] = pd.to_datetime(df['date_col'])
df['date_col_day'] = df['date_col'].dt.day
df['date_col_month'] = df['date_col'].dt.month
df['date_col_year'] = df['date_col'].dt.year

可以用一些更优雅的东西代替

for method in [day, month, year]:
    df[method.name] = df['date_col'].dt.method

我知道上面的示例在语法上是错误的,它只是演示了我想要的方式。

可以吗?

最佳答案

如果您有多个函数要作为“级联”调用,即:

  • y1 = fun1(df.x)
  • y2 = fun1(y1)
  • y3 = fun1(y2)

您可以使用y3 = df.pipe(fun1).pipe(fun2).pipe(fun3)

但就您而言,情况有所不同,因为您想保存 每个部分结果都在相关列中。

因此,您应该应用一个生成系列的函数,其中 相关索引下的每个部分结果。

示例:源 DataFrame 是:

     date_col  Xxx     Yyy
0  2019-01-12  100   97.37
1  2019-01-16  100   86.15
2  2019-01-20   80   80.00
3  2019-01-23  100  100.00

(date_colstring 类型)。

定义以下转换函数:

def conv(str):
    datTim = pd.to_datetime(str)
    return pd.Series([datTim, datTim.day, datTim.month, datTim.year],
        index=['date_col', 'date_col_day', 'date_col_month', 'date_col_year'])

并按以下方式应用它:

dtc = df.pop('date_col')
df = dtc.apply(conv).join(df)

请注意,pop 检索给定列,并将其从 df 中删除。 然后将 conv 应用于此列,生成一个 DataFrame,其中 4 列(日期及其“部分”)。最后一步是将其加入 源 DataFrame 的“其余部分”(dat_col 之后留下的列 已删除)。

现在date_coldatetime64类型,其内容是:

    date_col  date_col_day  date_col_month  date_col_year  Xxx     Yyy
0 2019-01-12            12               1           2019  100   97.37
1 2019-01-16            16               1           2019  100   86.15
2 2019-01-20            20               1           2019   80   80.00
3 2019-01-23            23               1           2019  100  100.00

关于python - 有没有一种优雅的方法可以在Python中调用同一对象的方法列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59518774/

相关文章:

python - OPENCV:Calibratecamera 2 重投影错误和自定义计算不一致

python - 覆盖rest-auth RegisterSerializer,添加年龄验证

python - 当参数在方括号中时,文档中的含义是什么?

python - 将 Pandas 列转换为日期时间

python - 如何绘制正确的分布 TreeMap ?

python - OpenCv, Python - 打印第一个发现的嘴巴

python - 如何将 boolean 值列表转换为单个 int,其中每个 boolean 值都被解释为位?

python - 列表比较算法 : How can it be made better?

python-3.x - 以下目录中的cx_freeze : can't find a usable init. tcl

python - 舍入 pandas.DataFrame 的正确方法?