【问题标题】:How to filter elements containing only specific repeated characters in a dataframe如何过滤数据框中仅包含特定重复字符的元素
【发布时间】:2019-05-23 15:19:51
【问题描述】:

我希望创建一个新的数据帧,以过滤掉先前数据帧中的冗余信息。原始数据框是通过查看许多文件夹并提供一列元素创建的,每个元素包含访问每个文件的完整路径的字符串。每个文件根据相应的测试文件夹中的试验编号和分数命名。我需要删除每次试验的分数为 100 的所有重复,但是每次试验的第一个 100 分数必须保留。

对于 python Pandas,我知道使用 df[df[col_header].str.contains('text')] 专门过滤掉需要的内容,并将“~”用作布尔 NOT。

带有冗余分数的未过滤数据框列看起来像这样

\\desktop\Test_Scores\test1\trial1-98
\\desktop\Test_Scores\test1\trial2-100
\\desktop\Test_Scores\test1\trial3-100       #<- must remove
\\desktop\Test_Scores\test2\trial1-95
\\desktop\Test_Scores\test2\trial2-100
\\desktop\Test_Scores\test2\trial3-100       #<- must remove
\\desktop\Test_Scores\test2\trial3-100       #<- must remove
.
.
.
n

使用一些代码作为过滤器后的预期结果将是一个看起来像这样的数据帧

\\desktop\Test_Scores\test1\trial1-98
\\desktop\Test_Scores\test1\trial2-100
\\desktop\Test_Scores\test2\trial1-95
\\desktop\Test_Scores\test2\trial2-100
.
.
.
.
n

【问题讨论】:

    标签: python pandas python-2.7 dataframe


    【解决方案1】:

    这一行应该可以解决您的问题。

    df = df.loc[df["col"].shift().str.contains("-100") != df["col"].str.contains("-100")]
    

    更新:

    df["col"] = df["col"].str.replace('\t','\\t')
    df['test_number'] = df.col.str.split('-').str[0].str.split('\\').str[-2]
    df['score'] = df.col.str.split('-').str[1]
    df.drop_duplicates(["test_number","score"], inplace = True)
    df.drop(["test_number","score"],1,inplace = True)
    

    检查此解决方案。我在第一行进行替换的原因是您的数据包含\t,在编程中它是一个制表符分隔符。

    【讨论】:

    • 如果您的连续组全部为 100,这将不起作用 - 它会从下一个组中删除项目。
    • 您的回复速度让我感到惊讶,谢谢。经过微小的修改,它可以编译并给出结果,我现在正在检查它们是否是所描述的预期结果。
    • 我不熟悉 df.shift.str 命令。似乎使用此功能跳过了一些低于 100 的分数,尽管它执行了部分任务。包含 100 的数字如果给出相同的测试编号,目前不会重复(这很好)
    • 它基本上是按索引移动数据。您可以通过创建一列的临时数据框并对其进行转换来了解它是如何工作的。 pandas.pydata.org/pandas-docs/stable/reference/api/…
    • df.loc函数会不会忽略同一个测试数下的多个试验分数低于100?
    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 2019-04-11
    • 2019-06-16
    • 2018-11-02
    • 2019-06-01
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多