python - 在保留标题的同时附加 2 个数据集
问题描述
我正在尝试从 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
同时保留标题(第一行)。请告知我该怎么做?
谢谢 !
解决方案
你想使用concat。
combined_df = pd.concat([df1, df2], ignore_index=True)
combined_df.to_excel('filename.xlsx',index=False)
推荐阅读
- python-3.x - 如何将 DataFrame(包括数组)中的两列与 CSV(Dataframe/Dictionary)中的两列匹配
- python - 在类外调用变量
- can-bus - 在 CANopen 中发送超过 8 字节数据的事件(异步数据)
- javascript - DJANGO:如何在views.py中获取表单值而不提交它
- pyspark - 根据其他列的值将小时数添加到数据框中的时间戳列
- java - java - 如何使用java swing中其他包中不同类的数据更新UI
- python - 熊猫系列中的熊猫数据框
- python - 仅当具有多个不同值时,如何基于其他列删除行
- android - 迁移到 Jetpack 撰写错误:不允许未绑定符号
- python - 无法理解如何在以下代码中通过列表切片将字符串中的字符分配给列表