SyntaxError:无法分配给函数调用--Python

时间:2018-04-09 10:18:42

标签: python-3.x machine-learning

我想通过生成交叉表来自动分配值。但我得到“SyntaxError:无法分配给函数调用”错误。

For example:
table_1 = pd.crosstab(data_new[target],data_new['col_1'])
table_2 = pd.crosstab(data_new[target],data_new['col_2'])
table_3 = pd.crosstab(data_new[target],data_new['col_3'])

这是必不可少的,因为我不知道我需要为交叉表做多少列(我不需要对所有列都这样做)。

我的代码:

df = pd.DataFrame({'col_x':[1,2,3,4],
               'col_y':[5,6,5,6],
               'col_z':[7,7,7,7],
               'col_a':[1,1,1,1],
               'col_b':[4,5,4,5],
               'col_1':[0,0,1,1]})

col_list = [ 'col_x', 'col_y', 'col_z']
target = ['col_1']
for i in range(len(col_list)):
    "table_" + str(i)=pd.crosstab(df[target].iloc[:,0],df[col_list[i]])

File "<ipython-input-108-6d57787a1172>", line 4
"table_" + str(i) = pd.crosstab(df[target].iloc[:,0],df[col_list[i]])
^
SyntaxError: can't assign to operator

非常感谢任何帮助。

得到了答案。谢谢 !!!

2 个答案:

答案 0 :(得分:0)

我得到了答案

col_list = [ 'col_x', 'col_y', 'col_z']
target = ['col_1']

for i in range(len(col_list)):
    key = 'table_{}'.format(i)
    value = pd.crosstab(df[target].iloc[:,0],df[col_list[i]])
    exec("{} = value".format(key))

答案 1 :(得分:0)

您收到语法错误,因为

"table_" + str(i)=pd.crosstab(df[target].iloc[:,0],df[col_list[i]])

赋值运算符的左侧和右侧都是表达式

我认为你可能需要使用字典来存档它,例如

dictionnary = {}
for x in range(1,10):
        dictionnary ["table_{}".format(x)]="Hello"

如果你打印字典

{'table_2': 'Hello', 'table_3': 'Hello','table_1': 'Hello'............

适合您的情况

col_list = [ 'col_x', 'col_y', 'col_z']
target = ['col_1']
dictionnary = {}
for i in range(len(col_list)):
    dictionnary ["table_{}".format(i)]=pd.crosstab(df[target].iloc[:,0],df[col_list[i]])
相关问题