[英]python string formatting variables' names from a list
Hi everyone I'm trying to define a set of variables and I want to format their names. 大家好,我正在尝试定义一组变量,我想格式化它们的名称。
The set up is: 设置为:
features=['Gender','Age','Rank'] + other11columns #selected columns of my data
In [1]:data['Gender'].unique()
Out[1]: array([0, 1], dtype=int64)
In [2]:data['Age'].unique()
Out[2]: array([10, 20, 30, 40, 50], dtype=int64)
In [3]:data['Rank'].unique()
Out[3]: array([0, 1, 2, 3, 4, 5, 6], dtype=int64)
.....
first I want to set up some empty data frames with each tag. 首先,我想为每个标签设置一些空的数据框。 I want something like these: 我想要这样的东西:
report_Gender
Out[3]:
Prediction Actual
0 NaN NaN
1 NaN NaN
report_Age
Out[5]:
Prediction Actual
10 NaN NaN
20 NaN NaN
30 NaN NaN
40 NaN NaN
50 NaN NaN
report_Rank
Out[6]:
Prediction Actual
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN
4 NaN NaN
5 NaN NaN
6 NaN NaN
.......
The following code doesn't work but indicates what I want to do 以下代码不起作用,但表明我想做什么
for i in range(len(features)-1):
report_features[i]=pd.DataFrame(index=data[feature[i]].unique(),columns=['Prediction','Actual'])
I tried to play with the string formatting with %s operation but didn't figure out how to put in variables' name... any help is appreciated :) 我试图通过%s操作来处理字符串格式,但是没有弄清楚如何输入变量的名称...可以提供任何帮助:)
Dynamically creating global variables can get hairy. 动态创建全局变量可能会很麻烦。 It is much easier if you put it in a smaller scope ==> any object, eg, a dictionary. 如果将它放在较小的范围内==>任何对象(例如字典),则容易得多。 You can achieve what you want like this 你可以像这样实现你想要的
my_dictionary = dict()
for f in features:
my_dictionary['report_{}'.format(f)] = pd.DataFrame(index=data[f].unique(),columns=['Prediction','Actual'])
You can access the df like my_dictionary['report_Gender']
for example. 例如,您可以像my_dictionary['report_Gender']
这样访问df。
Another way would be to create a class: 另一种方法是创建一个类:
class Reports:
pass
for f in features:
setattr(Reports, 'report_{}'.format(f), pd.DataFrame(index=data[f].unique(),columns=['Prediction','Actual'])
Then access as Reports.report_Gender
etc... 然后以Reports.report_Gender
等身份访问...
You can use the setattr method if you really wan't to do it but I'll suggest to follow Ravi Patel's advice 如果您确实不想这样做,可以使用setattr方法,但我建议您遵循Ravi Patel的建议
for i in range(len(features)-1):
setattr(object_method_or_module_your_variable_belong,
name_for_you_varialbe,
pd.DataFrame(index=data[feature[i]].unique(),columns=['Prediction','Actual'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.