Map List of Tuples to New Column

前端 未结 2 518
一向
一向 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

    0 讨论(0)
  • 2021-01-22 11:23

    Does this example help?

    class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
    
    >>> d = {'col1': ts1, 'col2': ts2}
    >>> df = DataFrame(data=d, index=index)
    >>> df2 = DataFrame(np.random.randn(10, 5))
    >>> df3 = DataFrame(np.random.randn(10, 5),
    ... columns=['a', 'b', 'c', 'd', 'e'])
    
    0 讨论(0)
提交回复
热议问题