我有以下数据框:
a b x
0 id1 abc 123 tr 2
1 id2 abd1 124 tr 6
2 id3 abce 126 af 9
3 id4 abe 128 nm 12
从b列中,对于每一项,我需要在第一个空格之前提取子字符串.因此,我需要以下结果:
list_of_strings = [abc, abd1, abce, abe]
请告知
我有以下数据框:
a b x
0 id1 abc 123 tr 2
1 id2 abd1 124 tr 6
2 id3 abce 126 af 9
3 id4 abe 128 nm 12
从b列中,对于每一项,我需要在第一个空格之前提取子字符串.因此,我需要以下结果:
list_of_strings = [abc, abd1, abce, abe]
请告知
使用具有^\S+
(锚定在字符串开头的非空格字符)和str.extract
的正则表达式:
df['b'].str.extract(r'^(\S+)', expand=False)
输出:
0 abc
1 abd1
2 abce
3 abe
Name: b, dtype: object
有关列表,请访问:
list_of_strings = df['b'].str.extract(r'^(\S+)', expand=False).tolist()
# ['abc', 'abd1', 'abce', 'abe']