Add column in dataframe from list

前端 未结 5 753
死守一世寂寞
死守一世寂寞 2020-12-04 07:16

I have a dataframe with some columns like this:

A   B   C  
0   
4
5
6
7
7
6
5

The possible range of values in A are only from 0 to 7

5条回答
  •  余生分开走
    2020-12-04 08:12

    IIUC, if you make your (unfortunately named) List into an ndarray, you can simply index into it naturally.

    >>> import numpy as np
    >>> m = np.arange(16)*10
    >>> m[df.A]
    array([  0,  40,  50,  60, 150, 150, 140, 130])
    >>> df["D"] = m[df.A]
    >>> df
        A   B   C    D
    0   0 NaN NaN    0
    1   4 NaN NaN   40
    2   5 NaN NaN   50
    3   6 NaN NaN   60
    4  15 NaN NaN  150
    5  15 NaN NaN  150
    6  14 NaN NaN  140
    7  13 NaN NaN  130
    

    Here I built a new m, but if you use m = np.asarray(List), the same thing should work: the values in df.A will pick out the appropriate elements of m.


    Note that if you're using an old version of numpy, you might have to use m[df.A.values] instead-- in the past, numpy didn't play well with others, and some refactoring in pandas caused some headaches. Things have improved now.

提交回复
热议问题