【问题标题】:Python Pandas append dataframePython Pandas 追加数据框
【发布时间】:2018-05-14 11:04:38
【问题描述】:

我有一个案例,我将 UUID 列添加到 .csv 文件。同时,我正在检查源文件并将它们与处理后的文件进行比较——如果源文件中有额外的行,我计划将这些新行附加到目标文件中。我想追加而不覆盖文件的原因是需要保持先前处理的行的 UUID 相同。

所以对于附加行的情况,我检查源文件和目标文件的行数是否相同。如果不是,我使用等于目标文件中行数的行号的数据(来自源文件)创建新的数据框。

那时,我尝试将新创建的数据帧附加到目标数据帧,但它一直失败。我收到以下错误:

> RuntimeWarning: '<' not supported between instances of 'int' and
> 'str', sort order is undefined for incomparable objects   result =
> result.union(other)

我正在使用的代码如下:

import os, uuid
import pandas as pd


def process_files():
    source_dir = "C:\\Projects\\test\\raw"
    destination_dir = "C:\\Projects\\test\\processed"

    for file_name in os.listdir(source_dir):
        if file_name.endswith((".csv", ".new")):
            df_source = pd.read_csv(source_dir + "/" + file_name, sep=";")

            if os.path.isfile(destination_dir + "/" + file_name):
                df_destination = pd.read_csv(destination_dir + "/" + file_name, sep=",", header=None)

                if df_source.shape[0] != (df_destination.shape[0]):
                    df_newlines = pd.read_csv(source_dir + "/" + file_name, sep=";", skiprows=df_destination.shape[0], header=None)
                    df_newlines.insert(0, "uu_id", pd.Series([uuid.uuid4() for i in range(len(df_newlines))]))
                    df_destination.append(df_newlines, ignore_index=True)
                    df_destination.to_csv(destination_dir + "/" + file_name, sep=",", header=False, mode="w", index=False)
                else:
                    continue
            else:
                df_source.insert(0,"uu_id", pd.Series([uuid.uuid4() for i in range(len(df_source))]))
                df_source.to_csv(destination_dir + "/" + file_name, sep=",", header=False, mode="w", index=False)
        else:
            continue


process_files()

我检查了两个数据框的 dtypes,它们每列都匹配。我还强制将列重命名为具有相同的字符串,但这并不能解决问题。知道我在追加时做错了什么(注释掉追加行运行脚本没有问题)?

谢谢你和最好的问候, 博斯扬

【问题讨论】:

    标签: python pandas csv dataframe append


    【解决方案1】:

    免责声明:由于缺乏声望点,我不能发表评论

    通常情况下,append 不会在适当位置使用。因此,我建议说

    df_destination = df_destination.append(df_newlines, ignore_index=True)
    

    希望就是这样。

    除此之外,我建议使用os.walkfnmatch 来浏览文件。

    【讨论】:

    • 您好!感谢您的帮助 - 它确实解决了我的问题。另一方面,我同时做了一个解决方法(以防有人会发现它也有用)。我没有使用 append(),而是创建了缺少行的新数据框,然后使用了 .to_csv(),mode 参数设置为“a”。最好的问候,博斯扬
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多