【问题标题】:how to fill up data with given rows from another file in python如何用python中另一个文件中的给定行填充数据
【发布时间】:2020-10-12 02:07:22
【问题描述】:

假设我有 100 个 txt 文件,每个文件有 20000 条记录,我想让每个文件有 25000 条记录,如何用另一个文件填充数据以获得每个文件有 25000 条记录?

【问题讨论】:

  • 将所有文件作为一个 pandas 数据帧读入,然后将它们分成 25000 行的块并再次写入文件。
  • 会慢吗?请给我一些示例代码,非常感谢
  • 可以真快,开始here
  • 我的是*txt文件,我没有发现那个链接包含任何数字,我需要把每个20000条记录的文件都改成25000条记录。

标签: python pandas numpy file


【解决方案1】:

当它们都在一个目录中时,使用这个:

import os
import pandas as pd

path = "path/to/directory/"
dfs = []  # list of dataframes

for file in os.listdir(path):
    if file.endswith(".txt"):
        # edit with you separator of choice
        dfs.append(pd.read_csv(file, sep=" ")

# edit with your axis of choice
# ignore axis is important so you don't have multiple indices
full_df = pd.concat(dfs, axis=0, ignore_index=True)

l = len(full_df)
n_dfs = l // 25000 + 1  # new number of dfs
for i in range(ndfs):
    if i < (n_dfs - 1):
        new_df = full_df[i * 25000: (i+1) * 25000]
    else:
        new_df = full_df[i * 25000:]
    new_df.to_csv("path/to/new_df/file.txt", header=None, index=None, sep=' ', mode='a')

应该这样做。

【讨论】:

  • 我现在就试试,非常感谢@Dorian,如果我想把25000改成22000怎么办,我可以写一个用户定义的函数,以便以后更容易改变参数吗?
  • 所有文件都在同一个目录下,此脚本会将所有记录写入一个txt文件?
  • 当然,您可以将 25000 更改为您想要的任何数字。您显然必须在循环中更改文件的名称,这样您就不会覆盖原始文件。
  • 我有几个表头,需要显示,你知道怎么改吗?
  • 这超出了原始问题的范围,关闭这个问题并打开一个新问题可能是有意义的。我也不知道你改变标题是什么意思 - 列?订购?什么标题?
猜你喜欢
  • 2021-09-24
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2020-06-23
  • 2021-10-27
  • 1970-01-01
相关资源
最近更新 更多