python:从用户定义函数返回数据帧时遇到问题(可能是用户错误)
我有一个创建数据帧的函数。在功能范围内,我可以将其打印出来。但是我在返回过程中做了一些错误的事情,因为我似乎无法在运行函数后调用DataFrame。下面是我的伪代码和附加的错误python:从用户定义函数返回数据帧时遇到问题(可能是用户错误),python,function,Python,Function,我有一个创建数据帧的函数。在功能范围内,我可以将其打印出来。但是我在返回过程中做了一些错误的事情,因为我似乎无法在运行函数后调用DataFrame。下面是我的伪代码和附加的错误 import pandas as pd def testfunction(new_df_to_output): new_df_to_output = pd.DataFrame() S1 = pd.Series([33,66], index=['a', 'b']) S2 = pd.Series([2
import pandas as pd
def testfunction(new_df_to_output):
new_df_to_output = pd.DataFrame()
S1 = pd.Series([33,66], index=['a', 'b'])
S2 = pd.Series([22,44], index=['a', 'b'])
S3 = pd.Series([11,55], index=['a', 'b'])
new_df_to_output = new_df_to_output.append([S1, S2, S3], ignore_index=True)
print new_df_to_output
print type(new_df_to_output)
print dir()
return new_df_to_output
testfunction('Desired_DF_name')
print dir()
print Desired_DF_name
数据帧在函数中正确打印。目录显示函数之后不会返回数据帧。尝试打印该数据帧返回以下错误
回溯最近一次呼叫上次:
文件functiontest.py,第21行,在
打印所需的_DF_名称
名称错误:未定义名称“所需名称”
我确信这是一个简单的错误,但在搜索Stackoverflow和python教程之后,我找不到解决方案。非常感谢您的指导。在testfunction内部,变量new_df_to_output本质上是一个标签,您将其分配给传入的对象
testfunction'Desired_DF_name'不会做您认为的事情;它将字符串“Desired_DF_name”的值分配给变量new_DF_to_output;它并没有创建一个名为required_DF_name的新变量。基本上,这与将新的_-df-u写入到_-output='required_-df-u-name'是一样的
您希望将从函数返回的数据帧保存到变量中。所以不是
testfunction('Desired_DF_name')
你想要
def testfunction():
...
Desired_DF_name = testfunction()
您可以更改testfunction的定义,以删除新的_df_to_输出参数。函数没有对它做任何操作,因为您立即重新分配变量:new_df_to_output=pd.DataFrame。我想您真的想要这样的东西:
import pandas as pd
def testfunction():
result = pd.DataFrame()
S1 = pd.Series([33,66], index=['a', 'b'])
S2 = pd.Series([22,44], index=['a', 'b'])
S3 = pd.Series([11,55], index=['a', 'b'])
result.append([S1, S2, S3], ignore_index=True)
return result
Desired_DF_name = testfunction()
您应该仔细阅读文档中的和。可能的副本谢谢您抽出时间。你的回答很有帮助。不过,我想说的是,我在PostInd之前阅读了这两个链接和stackoverflow建议的问题,不明白您和0x5453解释了什么。也许它就在那里,而我却装聋作哑。再次感谢您的时间。文档详细介绍了不返回值的函数和返回值的函数之间的区别:来自其他语言,您可能会反对fib不是函数而是过程,因为它不返回值。我认为您只需要更仔细地阅读文档并键入示例。谢谢。我所看到的所有文档或示例都没有像您那样清楚地说明我的错误。