在字符串列中删除单词并替换字符

2024-09-30 14:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要更改已导入的数据帧的DSFS列中的值。你知道吗

MemberID,Year,DSFS,DrugCount
48925661,Y2,9-10 months,7+
90764620,Y3,8- 9 months,3
61221204,Y1,2- 3 months,1

例如,“9-10个月”需要改为9-10。你知道吗

我该怎么做?你知道吗


Tags: 数据yeary1y2monthsy3dsfsdrugcount
3条回答

如果你能使用迭代器那就更好了。但这些是逗号分隔的值。只要巧妙地使用split()。如下所示

cleaned = [line.split(",")[2].replace("-", "_") for line in source]

其中source如果是一个文件对象、一大串字符串或一个发出字符串的迭代器(最好的一个)

试试这个:

In [175]: df.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+)': r'\1_\2'}}, regex=True)
Out[175]:
   MemberID Year         DSFS DrugCount
0  48925661   Y2  9_10 months        7+
1  90764620   Y3   8_9 months         3
2  61221204   Y1   2_3 months         1

到位:

In [176]: df
Out[176]:
   MemberID Year         DSFS DrugCount
0  48925661   Y2  9-10 months        7+
1  90764620   Y3  8- 9 months         3
2  61221204   Y1  2- 3 months         1

In [177]: df.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+)': r'\1_\2'}}, regex=True, inplace=True)

In [178]: df
Out[178]:
   MemberID Year         DSFS DrugCount
0  48925661   Y2  9_10 months        7+
1  90764620   Y3   8_9 months         3
2  61221204   Y1   2_3 months         1

如果只想保留数字,可以这样做:

In [183]: df.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+).*': r'\1_\2'}}, regex=True)
Out[183]:
   MemberID Year  DSFS DrugCount
0  48925661   Y2  9_10        7+
1  90764620   Y3   8_9         3
2  61221204   Y1   2_3         1

我没有安装pandas,但是解决方案应该适用于df对象。你知道吗

string="48925661,Y2,9-10 months,7+"
"_".join(re.findall(r'\b\d+\b', string.split(",")[2]))

试验结果:

>>> "_".join(re.findall(r'\b\d+\b', string.split(",")[2]))
'9_10'

python脚本:

$ cat test.py
with open("sample.csv") as inputs:
    next(inputs)  # skip the first line
    for line in inputs:
        parts = line.strip().split(",")
        parts[2] = "_".join(re.findall(r'\b\d+\b', parts[2]))
        print(",".join(parts))

结果:

$python test.py                                
48925661,Y2,9_10,7+
90764620,Y3,8_9,3
61221204,Y1,2_3,1

相关问题 更多 >