【问题标题】:Data Cleaning with Pandas使用 Pandas 进行数据清理
【发布时间】:2021-07-01 04:46:03
【问题描述】:
我有一个由文本数据组成的数据框列,我需要根据以下条件对其进行过滤:
- 字符“M”,如果出现在字符串中,只能在n-2位
- 字符串的 n-1 位置必须始终为“D”。
例如:
KFLL
KSDS
KMDK
MDDL
在这种情况下,例如,我必须删除第一个字符串,因为 n-1 位置的字符不是“D”,最后一个,因为字符“M”出现在n-2 位。
如何将其应用于整个数据框列?
【问题讨论】:
标签:
python
pandas
data-mining
data-cleaning
【解决方案1】:
这里有一个列表理解:
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']
【解决方案2】:
这就是你想要的。使用列表推导可能会写得更短,但至少这是可读的。它假定字符串都超过 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
【解决方案3】:
感谢大家的帮助。
我最终是这样实现的:
l = {"Sequence": [ 'KFLL', 'KSDS', 'KMDK', '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