Appending 2 data sets whilst keeping the header

Viewed 32

I am trying to extract a few items from an Excel file and subsequently save them into a separate Excel file.

For example, I am trying to:

  1. Select only transactions that is 500 and above from Column G
  2. Randomly select 3 transactions from the remaining items in the original Excel file
  3. Save these transactions into a new Excel file
  4. I need the heading (first row) in this new Excel file
A  B  C  D  E  F   G
x  x  x  x  x  x  100
x  x  x  x  x  x  10
x  x  x  x  x  x  500
x  x  x  x  x  x  1000
x  x  x  x  x  x  20
x  x  x  x  x  x  10
x  x  x  x  x  x  10
x  x  x  x  x  x  30
x  x  x  x  x  x  50

I am thinking if I could use the Append function ? I am not really sure how to work on it.

import pandas as pd 
import numpy as np 
import openpyxl 
from numpy.random import choice

df = pd.read_excel('filepath', sheet_name = 'Sheet1')

df1 = df[df['G'] >= 500]
df2 = df.loc[choice(df.index,3)]

## After appending df1 and df2
.to_excel('filename.xlsx',index=False) # to save to new Excel file

I am unsure on how to append df1 and df2 whilst keeping the header (first row). Please advise how can i do it ?

Thanks !

1 Answers

You want to use concat.

combined_df = pd.concat([df1, df2], ignore_index=True)
combined_df.to_excel('filename.xlsx',index=False)
Related