首页 > 解决方案 > 在保留标题的同时附加 2 个数据集

问题描述

我正在尝试从 Excel 文件中提取一些项目,然后将它们保存到单独的 Excel 文件中。

例如,我正在尝试:

  1. 从 G 列中仅选择 500 及以上的交易
  2. 从原始Excel文件的剩余项目中随机选择3笔交易
  3. 将这些交易保存到新的 Excel 文件中
  4. 我需要这个新 Excel 文件中的标题(第一行)
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

我在想是否可以使用 Append 功能?我不确定如何处理它。

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

我不确定如何附加df1df2同时保留标题(第一行)。请告知我该怎么做?

谢谢 !

标签: pythonexcelpandasnumpy

解决方案


你想使用concat

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

推荐阅读