1

Suppose that I have a pandas dataframe, df1:

import pandas as pd    
df1col = ['col1', 'col2']
df1 = pd.DataFrame(columns=df1col)
df1.loc[0] = 'a', 'b'

My goal is to create df2 where the first two columns of df2 are the same as those in df1. I use the names of the columns and append the column names of col3 and col4 on (is there a better way to do this?) and create the dataframe, df2:

df2col = df1col
df2col.append('col3')
df2col.append('col4')
df2 = pd.DataFrame(columns=df2col)

Now I simply want to add the first (and only) row of df1 to the first row of df2 AND I want to add two new entries (c and d) so that all the columns are filled. I've tried:

df2.loc[0] = df1.loc[0], 'c', 'd'

and

df2.loc[0] = [df1.loc[0], 'c', 'd']

But neither works. Any hints?

2
  • Do you want the data as well or df2 to have df1's column names? and also what are the columns c and d filled with? Commented Aug 25, 2015 at 22:59
  • Both. I think that this code successfully creates df2, which has column names from df1 plus two new column names. Now I want to create one row in df2 that takes the values from row 0 of df1 for the first two columns (a and then b). The third column will be c and the fourth d. Commented Aug 25, 2015 at 23:02

3 Answers 3

1

You can extract the list and then add 'c' and 'd' to it:

df2.loc[0] = df1.loc[0].tolist() + ['c', 'd']

>>> df2
  col1 col2 col3 col4
0    a    b    c    d
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that df1.loc[0] is an object, not a pair of values outside of any structure. You can fix it by extracting the values from df1.loc[0] and extending them with 'c' and 'd' as follows:

row1 = [val for val in df1.loc[0]]
row1.extend(['c', 'd'])
df2.loc[0] = row1

Comments

1

You can copy a dataframe and to add a column to a dataframe works like a dictionary.

import pandas as pd    
df1col = ['col1', 'col2']
df1 = pd.DataFrame(columns=df1col)
df1.loc[0] = 'a', 'b'
df2 = df1.copy()
df2['col3'] = 'c'
df2['col4'] = 'd'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.