python - Pandas 方法在整个 DataFrame 上应用函数

标签 python pandas function dataframe apply

我创建了一个函数,我需要传递数据帧,我得到形状并返回 df.head()

    def shape_of_df(df):
        tup = df.shape
        print('Shape of df  is Rows :{0[0]},column:{0[1]}'.format(tup))
        return df.head()

现在,当我使用 items.apply(shape_of_df) 调用函数时,我会收到错误,但是如果我调用函数并传递 df 作为参数,它就可以正常工作。请让我知道当我使用 df.apply() 时我错过了一些非常基本的东西,无法在文档中弄清楚

   shape_of_df(items) # this works fine prints shape and df.head()

最佳答案

文档的第一行解释说 DataFrame.apply将“沿 DataFrame 的轴应用函数”(即沿行或沿列)。

您想在整个数据帧上应用一个函数,所以如果您尝试链接函数,您应该查看 DataFrame.pipe 。用法类似:

items.pipe(shape_of_df)

只要满足 shape_of_df 接受 DataFrame 作为输入并相应返回一个 DataFrame 作为输出的条件即可。

关于python - Pandas 方法在整个 DataFrame 上应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51007852/

相关文章:

python - 改变值检测 numpy Python

python - 自动更新字段的最佳做法是什么?

python2.7.8 : TypeError: expected string or buffer with bs4 and re

c++ - 有没有一种检查 C++ 中常见子字符串的好方法?

c# - 在文本框中添加数字

python - 匹配数字或 100% 但不是 99% 的正则表达式

python - 奇怪的 cmap background_gradient 行为

python - 将小时(00 到 23)添加到日期列

python - Pandas 数据帧值拒绝被评估为带有 `.apply(eval)` 的 float 。为什么?

java - 调用函数给出 "NoSuchElementException"