Is it possible to add several columns at once to a pandas DataFrame?

后端 未结 4 1730
走了就别回头了
走了就别回头了 2020-12-01 13:55

If I want to create a new DataFrame with several columns, I can add all the columns at once -- for example, as follows:

data = {\'col_1\': [0, 1, 2, 3],
             


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 14:51

    If you don't want to create new DataFrame from additional_data, you can use something like this:

    >>> additional_data = [[8, 9, 10, 11], [12, 13, 14, 15]]
    >>> df['col3'], df['col4'] = additional_data
    >>> df
       col_1  col_2  col3  col4
    0      0      4     8    12
    1      1      5     9    13
    2      2      6    10    14
    3      3      7    11    15
    

    It's also possible to do something like this, but it would be new DataFrame, not inplace modification of existing DataFrame:

    >>> additional_header = ['col_3', 'col_4']
    >>> additional_data = [[8, 9, 10, 11], [12, 13, 14, 15]]
    >>> df = pd.DataFrame(data=np.concatenate((df.values.T, additional_data)).T, columns=np.concatenate((df.columns, additional_header)))
    >>> df
       col_1  col_2  col_3  col_4
    0      0      4      8     12
    1      1      5      9     13
    2      2      6     10     14
    3      3      7     11     15
    

提交回复
热议问题