我创建了一个函数,我需要传递数据帧,我得到形状并返回 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/