python pandas replacing strings in dataframe with numbers

前端 未结 9 1594
名媛妹妹
名媛妹妹 2020-12-08 04:22

Is there anyway to use the mapping function or something better to replace values in an entire dataframe?

I only know how to perform the mapping on series.

I

9条回答
  •  忘掉有多难
    2020-12-08 04:41

    You can use the applymap DataFrame function to do this:

    In [26]: df = DataFrame({"A": [1,2,3,4,5], "B": ['a','b','c','d','e'],
                             "C": ['b','a','c','c','d'], "D": ['a','c',7,9,2]})
    In [27]: df
    Out[27]:
       A  B  C  D
    0  1  a  b  a
    1  2  b  a  c
    2  3  c  c  7
    3  4  d  c  9
    4  5  e  d  2
    
    In [28]: mymap = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
    
    In [29]: df.applymap(lambda s: mymap.get(s) if s in mymap else s)
    Out[29]:
       A  B  C  D
    0  1  1  2  1
    1  2  2  1  3
    2  3  3  3  7
    3  4  4  3  9
    4  5  5  4  2
    

提交回复
热议问题