pandas dataframe adds single and multiple columns

dataframe add a single row

assign method

The dataframe assign method returns a new object (copy) without affecting the old dataframe object

    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)

Result display:

   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

Simple method and insert method

The simple method df['col_3'] = pd.Series([8, 9, 10, 11])
insert method df.insert(loc=len(df.columns), column=“col_4”, value=[8, 9, 10, 11])
This method will add new columns to the old 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 adds more columns

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)

Result display:

   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 can also match in one line

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

concat method

    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 method

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

join + dictionary

df = df.join(pd.DataFrame(
    {
    
    
        'column_new_1': np.nan,
        'column_new_2': 'dogs',
        'column_new_3': 3
    }, index=df.index
))

assign method

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

Soil method

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

Guess you like

Origin blog.csdn.net/qq_33873431/article/details/107464416