在python函数中返回数据框 [英] Returning a dataframe in python function

查看:289
本文介绍了在python函数中返回数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从python函数创建并返回数据框

I am trying to create and return a data frame from a python function

def create_df():
    data = {'state': ['Ohio','Ohio','Ohio','Nevada','Nevada'],
           'year': [2000,2001,2002,2001,2002],
           'pop': [1.5,1.7,3.6,2.4,2.9]}
    df = pd.DataFrame(data)
    return df
create_df()
df

我收到一个未定义df的错误。如果我将返回替换为打印,则可以正确打印数据框。有没有办法做到这一点?谢谢

I get an error that df is not defined. If I replace 'return' by 'print' I get print of the data frame correctly. Is there a way to do this? thanks

推荐答案

当您调用 create_df()时,python调用了该函数,但不会将结果保存在任何变量中。

when you call create_df() python calls the function but doesn't save the result in any variable. that is why you got the error.

create_df()的结果分配给 df 像这样 df = create_df()

assign the result of create_df() to df like this df = create_df()

这篇关于在python函数中返回数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆