【发布时间】:2021-11-28 06:44:15
【问题描述】:
我正在尝试从 Excel 文件中提取一些项目,然后将它们保存到单独的 Excel 文件中。
例如,我正在尝试:
- 从 G 列中仅选择 500 及以上的交易
- 从原始Excel文件的剩余项目中随机选择3笔交易
- 将这些交易保存到新的 Excel 文件中
- 我需要这个新 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
我不确定如何在保留标题(第一行)的同时附加 df1 和 df2。
请告知我该怎么做?
谢谢!
【问题讨论】:
-
没有尝试你的数据,但你可能可以使用 df = df1.append(df2) 获得你想要的数据框