我想通过生成交叉表来自动分配值。但是我遇到了“SyntaxError: can’t assign to function call”错误。
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
任何帮助都将不胜感激。
得到了答案。谢谢!!!
回答:
你遇到语法错误是因为
"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]])