Map List of Tuples to New Column

前端 未结 2 520
一向
一向 2021-01-22 10:35

Suppose I have a pandas.DataFrame:

In [76]: df
Out[76]: 
          a         b  c
0 -0.685397  0.845976  w
1  0.065439  2.642052  x
2 -0.220823 -2.0         


        
2条回答
  •  花落未央
    2021-01-22 11:20

    You need to turn your list of tuples into a dict which is ridiculously easy to do in python, then call map on it:

    In [4]:
    
    df['new'] = df['c'].map(dict(tp))
    df
    Out[4]:
                  a         b  c   new
    index                             
    0     -0.685397  0.845976  w  0.75
    1      0.065439  2.642052  x  0.50
    2     -0.220823 -2.040816  y  0.33
    3     -1.331632 -0.162705  z  0.25
    

    The docs for map show that that it takes as a function arg a dict, series or function.

    applymap takes a function as an arg but operates element wise on the whole dataframe which is not what you want to do in this case.

    The online docs show how to apply an operation element wise, as does the excellent book

提交回复
热议问题