Adding a column to a pandas dataframe containing the same value

I have a pandas dataframe A in size (1500.5) and a D dictionary containing:

D
Out[121]: 
{'newcol1': 'a',
 'newcol2': 2,
 'newcol3': 1}

for each key in the dictionary, I would like to create a new column in DataFrame A with the values ​​in the dictionary (the same value for all rows of each column)

at the end of A should be the size (1500.8)

Is there a python way to do this? thank!

+4
source share
2 answers

You can use concatwith constructor DataFrame:

D = {'newcol1': 'a',
 'newcol2': 2,
 'newcol3': 1}

df = pd.DataFrame({'A':[1,2],
                   'B':[4,5],
                   'C':[7,8]})

print (df)
   A  B  C
0  1  4  7
1  2  5  8

print (pd.concat([df, pd.DataFrame(D, index=df.index)], axis=1))
   A  B  C newcol1  newcol2  newcol3
0  1  4  7       a        2        1
1  2  5  8       a        2        1

Delay

D = {'newcol1': 'a',
 'newcol2': 2,
 'newcol3': 1}

df = pd.DataFrame(np.random.rand(10000000, 5), columns=list('abcde'))

In [37]: %timeit pd.concat([df, pd.DataFrame(D, index=df.index)], axis=1)
The slowest run took 18.06 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 875 ms per loop

In [38]: %timeit df.assign(**D)
1 loop, best of 3: 1.22 s per loop
+5
source

customization

A = pd.DataFrame(np.random.rand(10, 5), columns=list('abcde'))

d = {
    'newcol1': 'a',
    'newcol2': 2,
    'newcol3': 1
}

decision

Use assign

A.assign(**d)

          a         b         c         d         e newcol1  newcol2  newcol3
0  0.709249  0.275538  0.135320  0.939448  0.549480       a        2        1
1  0.396744  0.513155  0.063207  0.198566  0.487991       a        2        1
2  0.230201  0.787672  0.520359  0.165768  0.616619       a        2        1
3  0.300799  0.554233  0.838353  0.637597  0.031772       a        2        1
4  0.003613  0.387557  0.913648  0.997261  0.862380       a        2        1
5  0.504135  0.847019  0.645900  0.312022  0.715668       a        2        1
6  0.857009  0.313477  0.030833  0.952409  0.875613       a        2        1
7  0.488076  0.732990  0.648718  0.389069  0.301857       a        2        1
8  0.187888  0.177057  0.813054  0.700724  0.653442       a        2        1
9  0.003675  0.082438  0.706903  0.386046  0.973804       a        2        1
+4
source

Source: https://habr.com/ru/post/1667956/


All Articles