简体   繁体   English

使用'.format()'的模拟在Python中分配变量

[英]Assigning a variable in Python using analogue of '.format()'

I have a dataset with several columns of which I want to convert from categorical to numerical dtype. 我有一个数据集,其中有几列我想从分类转换为数字dtype。

I have defined the following function: 我已经定义了以下功能:

def create_num_column(df,column):
    df[str(column)]=df[str(column)].astype('category')
    df[str(column)+'_cat']=df[str(column)].cat.codes

    dictionary{}.format(str(column)+'_cat')=dict(zip(df[column],df[str(column)+'_cat']))
    return dictionary{}.format(str(column)+'_cat')

I also want this function to create a dictionary so I will be able to understand what label was assigned to what value. 我还希望这个函数创建一个字典,这样我就能理解为什么值分配了什么标签。

The problem here arises with naming of a dictionary as I have tried to use '.format()' and it has shown syntax error. 这里出现的问题是字典的命名,因为我试图使用'.format()'并且它显示了语法错误。

dictionary{}.format(str(column)+'_cat')=dict(zip(df.column,df[str(column)+'_cat'])) 字典{}。格式(STR(列)+ '_猫')=字典(拉链(df.column,DF [STR(柱)+ '_猫']))

>SyntaxError: invalid syntax > SyntaxError:语法无效

I understand that this particular method works with strings but is there any way to 'automate' the naming of variable? 我知道这个特殊的方法适用于字符串,但有没有办法'自动'变量的命名?

Thanks in advance. 提前致谢。

You cannot "dynamically" name a variable, and there is no need to do so. 您不能“动态”命名变量,也不需要这样做。 Simply return the dictionary: 只需返回字典:

def create_num_column(df,column):
    df[str(column)]=df[str(column)].astype('category')
    df[str(column)+'_cat']=df[str(column)].cat.codes

    return dict(zip(df.column,df[str(column)+'_cat']))

(There is a way to create variables or more generally objects with dynamic names in Python, but that's only very rarely useful.) (有一种方法可以在Python中创建具有动态名称的变量或更常见的对象,但这种方法很少有用。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM