我的网站

pandas dataframe 新增单列和多列

https://blog.csdn.net/qq_33873431/article/details/107464416

dataframe 新增单列

assign方法

dataframe assign方法,返回一个新对象(副本),不影响旧dataframe对象


    import pandas as pd


    df = pd.DataFrame({

        'col_1': [0, 1, 2, 3],

        'col_2': [4, 5, 6, 7]

    })

    sLength = len(df['col_1'])

    df2 = df.assign(col_3=pd.Series([8, 9, 10, 11]).values)

    print(df)

    print(df2)


结果展示:


   col_1  col_2

0      0      4

1      1      5

2      2      6

3      3      7

   col_1  col_2  col_3

0      0      4      8

1      1      5      9

2      2      6     10

3      3      7     11


简单的方法和insert方法

简单的方法df[‘col_3’] = pd.Series([8, 9, 10, 11])

insert方法 df.insert(loc=len(df.columns), column=“col_4”, value=[8, 9, 10, 11])

这种方式会对旧的dataframe新增列


    import pandas as pd


    df = pd.DataFrame({

        'col_1': [0, 1, 2, 3],

        'col_2': [4, 5, 6, 7]

    })


    df['col_3'] = pd.Series([8, 9, 10, 11])

    print(df)

    df.insert(loc=len(df.columns), column="col_4", value=[8, 9, 10, 11])

    print(df)



dataframe 新增多列

list unpacking

    import pandas as pd

    import numpy as np


    df = pd.DataFrame({

        'col_1': [0, 1, 2, 3],

        'col_2': [4, 5, 6, 7]

    })


    df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]

    print(df)



结果展示:


   col_1  col_2  column_new_1 column_new_2  column_new_3

0      0      4           NaN         dogs             3

1      1      5           NaN         dogs             3

2      2      6           NaN         dogs             3

3      3      7           NaN         dogs             3



DataFrame也可以一行匹配

 df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)

1

concat方法

    df = pd.concat(

        [

            df,

            pd.DataFrame(

                [[np.nan, 'dogs', 3]],

                index=df.index,

                columns=['column_new_1', 'column_new_2', 'column_new_3']

            )

        ], axis=1

    )


join方法

df = df.join(pd.DataFrame(

    [[np.nan, 'dogs', 3]], 

    index=df.index, 

    columns=['column_new_1', 'column_new_2', 'column_new_3']

))


join + 字典

df = df.join(pd.DataFrame(

    {

        'column_new_1': np.nan,

        'column_new_2': 'dogs',

        'column_new_3': 3

    }, index=df.index

))


assign方法

df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)

1

土方法

    df['column_new_1'] = np.nan

    df['column_new_2'] = 'dogs'

    df['column_new_3'] = 3


文章知识点与官方知识档案匹配,可进一步学习相关知识

————————————————

版权声明:本文为CSDN博主「lovelife110」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_33873431/article/details/107464416

此文由 我的网站 编辑,未经允许不得转载!:首页 > 会·生活 » pandas dataframe 新增单列和多列

()
分享到:

相关推荐

评论 暂无评论