[英]I want to split a string by a character on its first occurence, which belongs to a list of characters. How to do this in python?
[英]I want to replace the string with the first occurence in list
我正在清理用于建模的数据,我想用列表中的第一个单词替换字符串中的多个单词。
任何人都可以帮助使用 Python 代码来解决这个问题吗?
数据:
id String
1 a;b
2 b;e
3 c;d
4 a;f
5 a;c;h
6 b;c;d
7 e;c
8 f;a;c
9 h;e;c
10 b;a;d
列表:
b
c
f
h
e
d
a
输出:
id Result
1 b
2 b
3 c
4 f
5 c
6 b
7 c
8 c
9 c
10 b
修改为适用于数据帧。
import pandas as pd
df = pd.DataFrame({
'id' : range(1,11),
'String' :('a;b','b;e','c;d','a;f','a;c;h','b;c;d','e;c','f;a;c','h;e;c','b;a;d'),
})
someList = ['b','c','f','h','e','d','a']
def firstOccurance(x):
for l in someList:
if l in x:
return l
break
df['String'] = df['String'].apply(firstOccurance)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.