Python 熊猫数据清理
我有一个由文本数据组成的dataframe列,需要根据以下条件对其进行过滤:Python 熊猫数据清理,python,pandas,data-mining,data-cleaning,Python,Pandas,Data Mining,Data Cleaning,我有一个由文本数据组成的dataframe列,需要根据以下条件对其进行过滤: 字符“M”,如果它出现在字符串中,则只能位于n-2位置 字符串的n-1位置必须始终为“D” 例: KFLL KSDS KMDK MDDL 例如,在这种情况下,我必须删除第一个字符串,因为n-1位置的字符不是“D”,而最后一个字符串,因为字符“M”出现在n-2位置之外 如何将其应用于整个数据帧列?下面是一个列表: l = ['KFLL', 'KSDS', 'KMDK', 'MDDL'] [x for x in l
- 字符“M”,如果它出现在字符串中,则只能位于n-2位置
- 字符串的n-1位置必须始终为“D”
如何将其应用于整个数据帧列?下面是一个列表:
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']
Sequence
0 KFLL
1 KSDS
2 KMDK
3 MDDL
4 MMMD
Sequence
1 KSDS
2 KMDK
这正是你想要的。也许可以用列表的理解写得更短,但至少这是可读的。它假定字符串都超过3个字符,否则将得到索引器。在这种情况下,您需要添加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', '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)
输出:
['KSDS', 'KMDK']
Sequence
0 KFLL
1 KSDS
2 KMDK
3 MDDL
4 MMMD
Sequence
1 KSDS
2 KMDK
到目前为止你试过什么?我没有看到任何尝试?