Replace string/value in entire DataFrame

前端 未结 3 1109
不知归路
不知归路 2020-12-01 00:25

I have a very large dataset were I want to replace strings with numbers. I would like to operate on the dataset without typing a mapping function for each key (column) in th

相关标签:
3条回答
  • 2020-12-01 01:14

    Use replace

    In [126]: df.replace(['very bad', 'bad', 'poor', 'good', 'very good'], 
                         [1, 2, 3, 4, 5]) 
    Out[126]: 
          resp  A  B  C
       0     1  3  3  4
       1     2  4  3  4
       2     3  5  5  5
       3     4  2  3  2
       4     5  1  1  1
       5     6  3  4  1
       6     7  4  4  4
       7     8  5  5  5
       8     9  2  2  1
       9    10  1  1  1
    
    0 讨论(0)
  • 2020-12-01 01:14

    data = data.replace(['very bad', 'bad', 'poor', 'good', 'very good'], [1, 2, 3, 4, 5])

    You must state where the result should be saved. If you say only data.replace(...) it is only shown as a change in preview, not in the envirable itself.

    0 讨论(0)
  • 2020-12-01 01:23

    Considering data is your pandas DataFrame you can also use:

    data.replace({'very bad': 1, 'bad': 2, 'poor': 3, 'good': 4, 'very good': 5}, inplace=True)
    
    0 讨论(0)
提交回复
热议问题