[英]Naming a Pandas dataframe
I'm guessing this is basic, but again I'm struggling.我猜这是基本的,但我又在挣扎。
I want to create a data frame from a .csv therefore I'm doing the obvious:我想从 .csv 创建一个数据框,因此我做的很明显:
df = pd.read_csv(file_path)
But in this case I want to give the data frame a meaningful name so in an IPython console I can do this:但在这种情况下,我想给数据框一个有意义的名字,所以在 IPython 控制台中我可以这样做:
my_dataframe_name = pd.read_csv(file_path)
My problem is that within a script, my_dataframe_name is a string defined elsewhere ie我的问题是在脚本中,my_dataframe_name 是在别处定义的字符串,即
some_variable = 'my_dataframe_name'
So (eventually...) my question is how can I create the dataframe and have it named using the string held in another variable?所以(最终......)我的问题是如何创建数据框并使用另一个变量中保存的字符串命名它?
Best Regards,此致,
Ben本
one way to do it is to use the exec function:一种方法是使用 exec 函数:
exec('%s = pd.read_csv(file_path)' % some_variable)
I don't know if there is a better way to do it, but this should solve your problem我不知道是否有更好的方法来做到这一点,但这应该可以解决您的问题
You can use globals()
to create global variable您可以使用globals()
创建全局变量
some_variable = 'my_dataframe_name'
globals()[some_variable] = pd.read_csv(file_path)
print(my_dataframe_name)
But I would rather keep it in dictionary但我宁愿把它放在字典里
all_dfs = {}
some_variable = 'my_dataframe_name'
all_dfs[some_variable] = pd.read_csv(file_path)
print(all_dfs[some_variable])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.