【问题标题】:Appending 2 data sets whilst keeping the header在保留标题的同时附加 2 个数据集
【发布时间】:2021-11-28 06:44:15
【问题描述】:

我正在尝试从 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。 请告知我该怎么做?

谢谢!

【问题讨论】:

  • 没有尝试你的数据,但你可能可以使用 df = df1.append(df2) 获得你想要的数据框

标签: python excel pandas numpy


【解决方案1】:

你想使用concat

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2020-10-11
    • 2014-04-23
    • 2018-09-09
    相关资源
    最近更新 更多