[英]Create new column if DataFrame contains specific string
I have one column
in the DataFrame
that is a name.我在
DataFrame
中有一个column
是一个名称。 Inside this name there are patterns that I want to locate, and create a category in other column
of same DataFrame
.在这个名称中,有我想要定位的模式,并在同一
DataFrame
其他column
中创建一个类别。 For example :例如 :
Name
name first RB LA a
name LB second
RB name third
name LB fourth
I want the name with the same pattern to be in the same category, displayed in the other column我希望具有相同模式的名称在同一类别中,显示在另一列中
What I want :我想要的是 :
Name Example
name first RB LA a Round Blade category
name LB second Long Biased category
RB name third Round Blade category
name LB fourth Long Biased category
I have a DataFrame
, not a list, there are several other columns in it.我有一个
DataFrame
,而不是一个列表,其中还有其他几个列。 And there are not only two categories, but several ones.而且不仅有两个类别,而且有几个类别。
What I have Tried :我试过的:
df.loc[df['Name']=="RB", 'Example'] = "RB category"
But it does not work since it must be an exact match但它不起作用,因为它必须完全匹配
Another attempt :另一种尝试:
if df[['Name'].str.contains("RB")] :
(...)
But it gives me error :但它给了我错误:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I tried to add to .bool()
or .any()
, but or the error persist or nothing happens when I run the line.我试图添加到
.bool()
或.any()
,但是当我运行该行时,错误仍然存在或没有任何反应。
Thank you.谢谢你。
You could use pandas.Series.str.extract
to achieve the desired output您可以使用
pandas.Series.str.extract
来实现所需的输出
import numpy as np
import pandas as pd
df = pd.DataFrame({
"Name": ["name first RB LA a", "name LB second", "RB name third", "name LB fourth"]
})
df["Example"] = df["Name"].str.extract("(LB|RB)")[0] + " category"
Name Example
0 name first RB LA a RB category
1 name LB second LB category
2 RB name third RB category
3 name LB fourth LB category
To change category names within Example
column use .str.replace
:要更改
Example
列中的类别名称,请使用.str.replace
:
df["Example"] = (df["Example"]
.str.replace("RB", "Round Blade")
.str.replace("LB", "Long Biased")
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.