0

I have two pandas dataframe like below.
df1:

  col1 col2    col3    col4
0   45   69  string  string

df2:

   col5    col8
0    45      37
1  data  random

I want to combine these two into one dataframe.
resultant df:

col1 col2    col3    col4
  45   69  string  string
--------- 1 or 2 empty rows here -------------
col5    col8
   45      37
 data  random

I tried the append method but that puts col5 and col8 as columns. I want to combine df1 and df2. col1, col2 and other column names don't even have to be column names in the resultant dataframe. They can be values in a row. I am trying to create a summary in the resultant dataframe.

Any help is appreciated. Thank you.

6
  • Have you read the docs? Pandas has concat, join and merge methods, have a look pandas.pydata.org/pandas-docs/stable/reference/api/… Commented Jun 14, 2022 at 15:41
  • A dataframe isn't ever going to be formatted like your desired output... they don't have randomly blank lines with new column names, that's just not how a dataframe works. Are you talking about exporting two dataframes in this format to a CSV or something? Commented Jun 14, 2022 at 15:44
  • This is not a code-writing or tutoring service. We can help solve specific, technical problems, not open-ended requests for code or advice such as "Any help is appreciated." With that as a caveat, the use of a dataframe for your expected results doesn't make sense. A DF is a collection of rows with arranged as columns of simial information. Leaving rows blank doesn't make sense in this context, nor does having a Column labeled Col1 with row data containing a col5 header. While it is valid to have mixed data types in a column this makes processing a df much more difficult. Commented Jun 14, 2022 at 15:45
  • @alec_djinn, Hi. I checked those methods too. Couldn't make it work. Commented Jun 14, 2022 at 16:03
  • @BeRT2me, Yes. I want to export it as csv. Commented Jun 14, 2022 at 16:05

1 Answer 1

1
# write first dataframe
df1.to_csv('file.csv')

# append empty line
with open('file.csv', 'a') as f:
    f.write('\n\n')

# append second dataframe
df2.to_csv('file.csv', mode='a')

Output:

,col1,col2,col3,col4
0,45,69,string,string

,col5,col8
0,45,37
1,data,random

Sign up to request clarification or add additional context in comments.

1 Comment

This worked well except it didn't add an empty row. Thanks. I added an empty row with df1=df1.append(pd.DataFrame([[''] * len(df1.columns)], columns=df1.columns)).

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.