使用 Pandas 进行数据清理

问题描述

我有一个由文本数据组成的数据框列,我需要根据以下条件对其进行过滤:

  • 字符“M”,如果出现在字符串中,只能出现在第n-2个位置
  • 字符串的 n-1 位置必须始终是“D”。

例如:

KFL

KSDS

KMDK

MDDL

在这种情况下,例如,我必须删除一个字符串,因为第 n-1 个位置的字符不是“D”,而最后一个,因为字符“M”出现在n-2个位置。

如何将其应用于整个数据框列?

解决方法

这里有一个列表理解:

l = ['KFLL','KSDS','KMDK','MDDL']

[x for x in l if ((('M' not in x) or (x[-3] == 'M')) and (x[-2] == 'D'))]

输出:

['KSDS','KMDK']
,

这就是你想要的。使用列表推导式可能会写得更短,但至少这是可读的。它假定字符串都长于 3 个字符,否则您会得到一个 IndexError。在这种情况下,您需要添加一个 try/except

from collections import Counter

import pandas as pd

df = pd.DataFrame(data=list(["KFLL","KSDS","KMDK","MDDL"]),columns=["code"])
print("original")
print(df)
mask = list()
for code in df["code"]:
    flag = False
    if code[-2] == "D":
        counter = Counter(list(code))
        if counter["M"] == 0 or (counter["M"] == 1 and code[-3] == "M"):
            flag = True
    mask.append(flag)
df["mask"] = mask
df2 = df[df["mask"]].copy()
df2.drop("mask",axis=1,inplace=True)
print("new")
print(df2)

输出看起来像这样

original
   code
0  KFLL
1  KSDS
2  KMDK
3  MDDL
new
   code
1  KSDS
2  KMDK
,

感谢大家的帮助。

我最终是这样实现的:

l = {"Sequence": [ 'KFLL','MDDL',"MMMD"]}

df = pd.DataFrame(data= l)

print(df)

df = df[df.Sequence.str[-2] == 'D']

df = df[~df.Sequence.apply(lambda x: ("M" in x and x[-3]!='M') or x.count("M") >1 )]

print(df)

输出:

  Sequence
0     KFLL
1     KSDS
2     KMDK
3     MDDL
4     MMMD
  Sequence
1     KSDS
2     KMDK