SyntaxError: 无法为函数调用赋值 – Python

我想通过生成交叉表来自动分配值。但是我遇到了“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]])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注