我需要更改导入数据的列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。
我该怎么做?
发布于 2016-04-05 21:03:05
试试这个:
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
发布于 2016-04-05 21:06:34
我没有安装熊猫,但解决方案应该是为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
发布于 2016-04-05 21:19:26
如果你能用一个迭代器会更好。但这些是逗号分隔的值。只要以一种巧妙的方式使用split()
即可。如下所示
cleaned = [line.split(",")[2].replace("-", "_") for line in source]
其中source
如果一个文件对象,一个大的字符串列表或一个迭代器发出字符串(最好的)
https://stackoverflow.com/questions/36436953
复制相似问题