亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用.map()在pandas DataFrame中有效創建其他列

使用.map()在pandas DataFrame中有效創建其他列

Helenr 2021-03-16 16:13:15
我正在分析形狀類似于以下示例的數據集。我有兩種不同類型的數據(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')]


查看完整回答
反對 回復 2021-03-24
  • 1 回答
  • 0 關注
  • 303 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號