4

I have a pandas dataframe A of size (1500,5) and a dictionary D 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 the dataframe A with the values in the dictionary (same value for all the rows of each column)

at the end A should be of size (1500,8)

Is there a "python" way to do this? thanks!

0

2 Answers 2

6

You can use concat with DataFrame constructor:

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

Timings:

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
Sign up to request clarification or add additional context in comments.

1 Comment

actually you could just do index=df.index here
5

setup

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

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

solution

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.