Add column in dataframe from list

前端 未结 5 746
死守一世寂寞
死守一世寂寞 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 07:57

    A solution improving on the great one from @sparrow.

    Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.

    Let's suppose you want to call your new column simply, new_column

    First make the list into a Series:

    column_values = pd.Series(mylist)
    

    Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column. In the following example we will position the new column in the first position from left (by setting loc=0)

    df.insert(loc=0, column='new_column', value=column_values)
    

提交回复
热议问题