我正在分析形狀類似于以下示例的數據集。我有兩種不同類型的數據(abc數據和xyz數據): abc1 abc2 abc3 xyz1 xyz2 xyz30 1 2 2 2 1 21 2 1 1 2 1 12 2 2 1 2 2 23 1 2 1 1 1 14 1 1 2 1 2 1我想創建一個為數據框中存在的每個abc列添加一個分類列的函數。使用列名列表和類別映射字典,我可以獲得所需的結果。abc_columns = ['abc1', 'abc2', 'abc3']xyz_columns = ['xyz1', 'xyz2', 'xyz3']abc_category_columns = ['abc1_category', 'abc2_category', 'abc3_category']categories = {1: 'Good', 2: 'Bad', 3: 'Ugly'}for i in range(len(abc_category_columns)): df3[abc_category_columns[i]] = df3[abc_columns[i]].map(categories)print df3最終結果: abc1 abc2 abc3 xyz1 xyz2 xyz3 abc1_category abc2_category abc3_category0 1 2 2 2 1 2 Good Bad Bad1 2 1 1 2 1 1 Bad Good Good2 2 2 1 2 2 2 Bad Bad Good3 1 2 1 1 1 1 Good Bad Good4 1 1 2 1 2 1 Good Good Bad雖然最后的for循環工作正常,但我覺得我應該使用Python的lambda函數,但似乎無法弄清楚。有沒有更有效的方法來映射動態數量的abc類型的列?
1 回答

慕仙森
TA貢獻1827條經驗 獲得超8個贊
您可以將applymap其與dictionaryget方法一起使用:
In [11]: df[abc_columns].applymap(categories.get)
Out[11]:
abc1 abc2 abc3
0 Good Bad Bad
1 Bad Good Good
2 Bad Bad Good
3 Good Bad Good
4 Good Good Bad
并將其放入指定的列:
In [12]: abc_categories = map(lambda x: x + '_category', abc_columns)
In [13]: abc_categories
Out[13]: ['abc1_category', 'abc2_category', 'abc3_category']
In [14]: df[abc_categories] = df[abc_columns].applymap(categories.get)
注意:您可以abc_columns使用列表推導來相對有效地構建:
abc_columns = [col for col in df.columns if str(col).startswith('abc')]
添加回答
舉報
0/150
提交
取消