这可能吗?
i = 1
for var in ['var1', 'var2', 'var3', 'var4']:
eval(var) = i
i + 1
我想以某种方式在每个循环中创建一个新名称的变量。
[编辑:] 很多人说,它没有用,所以下面是我想用于的实际代码:
import pandas as pd
# Convert categorical variables to dummies
PPE_WAW_DISTRICT = pd.get_dummies(X['PPE_WAW_DISTRICT'], prefix='PPE_WAW_DISTRICT')
PPE_TARIFF_TYPE = pd.get_dummies(X['PPE_TARIFF_TYPE'], prefix='PPE_TARIFF_TYPE')
PPE_OSD = pd.get_dummies(X['PPE_OSD'], prefix='PPE_OSD')
VariantProdEE = pd.get_dummies(X['VariantProdEE'], prefix='VariantProdEE')
CUS_OWNER = pd.get_dummies(X['CUS_OWNER'], prefix='CUS_OWNER')
CUS_LEGAL_FORM = pd.get_dummies(X['CUS_LEGAL_FORM'], prefix='CUS_LEGAL_FORM')
CUS_CITY = pd.get_dummies(X['CUS_CITY'], prefix='CUS_CITY')
CUS_DISTRICT = pd.get_dummies(X['CUS_DISTRICT'], prefix='CUS_DISTRICT')
X.drop(['PPE_WAW_DISTRICT', 'PPE_TARIFF_TYPE', 'PPE_OSD', 'CUS_OWNER',
'CUS_LEGAL_FORM', 'CUS_CITY', 'CUS_DISTRICT'], axis=1, inplace=True)
X = pd.concat([PPE_WAW_DISTRICT, PPE_TARIFF_TYPE, PPE_OSD, VariantProdEE,
CUS_OWNER, CUS_LEGAL_FORM, CUS_CITY, CUS_DISTRICT], axis=1)
基本上我想从每个选定的列创建虚拟列,然后使用前缀将其添加到主数据帧(X)
谢谢, 马特
答案 0 :(得分:1)
您几乎可以肯定不愿意这样做,但是如果出于某些原因您仍然真的想这样做
i = 1
for var in ['var1', 'var2', 'var3', 'var4']:
exec(var + "=" + str(i))
i += 1
或为了紧凑起见,
for i, var in enumerate(['var1', 'var2', 'var3', 'var4'], 1):
exec(var + "=" + str(i))
但是正如其他人所说的,请使用字典!