2017-08-27 56 views
1

我使用熊貓0.20.1和Python 3.6。
首先請檢查我的例子:
說我有一個名爲一個數據幀:通過循環和exec創建一系列映射()

up down 
0 a high 
1 a low 
2 b low 
3 c high 

每列都有一些字符串。我想要做的是將這些字符串轉換爲數字,並將每列的映射存儲在數據框中。 那就是:

up down 
0 0 0 
1 0 1 
2 1 1 
3 2 0 

,並存儲在列名+ '_CODE'。在我的例子的格式兩個名爲dataframes的映射,他們是up_codedown_code

up up_id 
0 a  0 
1 b  1 
2 c  2 

    down down_id 
0 high  0 
1 low  1 

我試過的是:

cols = ['up', 'down'] 
for col in cols: 
    exec("%(k)s_code = pd.DataFrame({%(k)s:a[col].unique(), %(k)s_id:range(len(a[col].unique()))})" % {'k':col}) 

我預計這將創建dataframes存儲映射,但它提出了一個名稱錯誤:

Traceback (most recent call last): 

    File "<ipython-input-81-7fc8a22fc7f1>", line 2, in <module> 
    exec("%(k)s_code = pd.DataFrame({%(k)s:a[col].unique(), %(k)s_id:range(len(a[col].unique()))})" % {'k':col}) 

    File "<string>", line 1, in <module> 

NameError: name 'up' is not defined 

我做了什麼錯在這裏?還是有更簡單的方法來實現它?

回答

1

字典的鍵必須是字符串,數字或變量與分配給它的東西。在你的情況下,當你使用exec方法創建變量時,請將代碼(k)s(k)s_id更改爲'(k)s''(k)s_id'

cols = ['up', 'down'] 
for col in cols: 
    exec("%(k)s_code = pd.DataFrame({'%(k)s':a[col].unique(), '%(k)s_id':range(len(a[col].unique()))})" % {'k':col}) 
+0

簡單而直接!謝謝Bharath! – Sean

+0

很高興幫助肖恩 – Dark