我有一个创建 DataFrame 的函数。在该功能中我可以将其打印出来。但我在返回过程中做错了,因为运行函数后我似乎无法调用 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([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
Run Code Online (Sandbox Code Playgroud)
DataFrame 在函数内正确打印。目录显示该函数之后没有返回DataFrame。尝试打印该数据帧返回返回以下错误
回溯(最近一次调用最后一次):文件“functiontest.py”,第 21 行,打印 Desired_DF_name NameError:名称“Desired_DF_name”未定义
我确信这是一个简单的错误,但在搜索 Stackoverflow 和 python 教程后我找不到解决方案。非常感谢任何指导。
在内部testfunction,变量new_df_to_output本质上是您分配给传入对象的标签。
testfunction('Desired_DF_name')不按你的想法做;它将字符串“Desired_DF_name”的值分配给变量new_df_to_output;它没有创建名为 的新变量Desired_DF_name。基本上和写作是一样的new_df_to_output = 'Desired_DF_name'。
您想要将从函数返回的 DataFrame 保存到变量中。所以而不是
testfunction('Desired_DF_name')
Run Code Online (Sandbox Code Playgroud)
你要
def testfunction():
...
Desired_DF_name = testfunction()
Run Code Online (Sandbox Code Playgroud)
(您可以更改 的定义testfunction以删除new_df_to_output参数。无论如何,该函数都没有对它执行任何操作,因为您立即重新分配了变量:new_df_to_output = pd.DataFrame()。)