我想在几列中拆分字符串。例如,我想在下面的数据框中从col2,col3和col5中选择一些信息(但实际上我有超过一百列的信息)。
d = pd.DataFrame({
'col1' : ['USA', 'AGN'],
'col2' : ['0|0:0.014:0.986,0.013,0', '1|0:0.02:1.936,0.023,1'],
'col3' : ['1|0:0.024:0.9,0.01345,2', '0|2:0.213:0.92,0.1,2'],
'col4' : ['done', 'done'],
'col5' : ['2|0:0.02:1.936,0.023,1', '1|0:0.024:0.9,0.01345,2']
})
col1 col2 col3 col4 .....
0 USA 0|0:0.014:0.986,0.013,0 1|0:0.024:0.9,0.01345,2 done .....
1 AGN 1|0:0.02:1.936,0.023,1 0|2:0.213:0.92,0.1,2 done .....
我只需要那个长字符串的前3个标记。然后我希望我可以从我的结果中看到如下。
col1 col2 col3 col4 col5 ....
USA 0|0 1|0 done 2|0 ....
AGN 1|0 0|2 done 1|0 ....
请提示吗?
答案 0 :(得分:2)
如果我理解你的问题,你可以这样做:
In [254]: d.replace(r':.*', '', regex=True)
Out[254]:
col1 col2 col3 col4 col5
0 USA 0|0 1|0 done 2|0
1 AGN 1|0 0|2 done 1|0
答案 1 :(得分:1)
获取前三个字符串字符:
>>> d.col2.str[:3]
0 0|0
1 1|0
Name: col2, dtype: object
要拆分“:”并取第一项:
>>> d.col2.str.split(':', expand=True)[0]
0 0|0
1 1|0
Name: 0, dtype: object
将其应用于一组列:
cols = ['col2', 'col3', 'col5']
d.loc[:, cols] = d.loc[:, cols].apply(lambda s: s.str[:3])
>>> d
col1 col2 col3 col4 col5
0 USA 0|0 1|0 done 2|0
1 AGN 1|0 0|2 done 1|0