Efficiently creating additional columns in a pandas DataFrame using .map()

前端 未结 1 1517
再見小時候
再見小時候 2021-02-01 06:29

I am analyzing a data set that is similar in shape to the following example. I have two different types of data (abc data and xyz data):

   abc         


        
相关标签:
1条回答
  • 2021-02-01 07:23

    You can use applymap with the dictionary get method:

    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
    

    And put this to the specified columns:

    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)
    

    Note: you can construct abc_columns relatively efficiently using a list comprehension:

    abc_columns = [col for col in df.columns if str(col).startswith('abc')]
    
    0 讨论(0)
提交回复
热议问题