Python 若现有列的值包含特定子字符串,则创建新的pd.DataFrame列
我有一个数据帧,如下所示:Python 若现有列的值包含特定子字符串,则创建新的pd.DataFrame列,python,pandas,dataframe,filter,Python,Pandas,Dataframe,Filter,我有一个数据帧,如下所示: entity 0 cat 1 dog 2 tree 3 dog 4 flower 我想创建一个名为type的新列,该列包含基于entity中的值包含子字符串的条件的值 substring1 = 'cat|og' substring2 = 'ree|ower' 生成的数据帧应如下所示: entity type 0 cat animal 1 dog
entity
0 cat
1 dog
2 tree
3 dog
4 flower
我想创建一个名为type
的新列,该列包含基于entity
中的值包含子字符串的条件的值
substring1 = 'cat|og'
substring2 = 'ree|ower'
生成的数据帧应如下所示:
entity type
0 cat animal
1 dog animal
2 tree plant
3 dog animal
4 flower plant
我采用的方法是采用pd.Series.str.contains,并创建两个布尔列is_animal
和is_plant
如何修改下面的代码以消除对两个布尔列的需要,而只使用type
列
df.loc[:, 'is_animal'] = df.entity.astype(str).str.contains(substring1, case=False)
df.loc[:, 'is_plant'] = df.entity.astype(str).str.contains(substring2, case=False)
我已尝试使用
iteritems()
在数据帧上迭代以创建类型
列,但它似乎不起作用。您可以按子字符串为类型
创建字典,然后通过比较子字符串
仅为匹配行设置新值:
d = {'animal':substring1, 'plant':substring2}
s = df.entity.astype(str)
for k, v in d.items():
df.loc[s.str.contains(v, case=False), 'type'] = k
print (df)
entity type
0 cat animal
1 dog animal
2 tree plant
3 dog animal
4 flower plant
您可以通过子字符串为
类型
s创建字典,然后通过比较子字符串
s仅为匹配行设置新值:
d = {'animal':substring1, 'plant':substring2}
s = df.entity.astype(str)
for k, v in d.items():
df.loc[s.str.contains(v, case=False), 'type'] = k
print (df)
entity type
0 cat animal
1 dog animal
2 tree plant
3 dog animal
4 flower plant