【问题标题】:how to use contains when: AttributeError: 'str' object has no attribute 'contains'如何使用包含时:AttributeError:'str'对象没有属性'contains'
【发布时间】:2020-12-12 06:23:45
【问题描述】:

我喜欢循环检查单元格是否包含“Ac”或“Vt 字符串”

那是我的 df

data={"col1":[2,3,4,5],
"col2":[4,2,4,6],
"col3":[7,6,9,11],
"col4":[14,11,22,8],
"name":["Acsd","Adgf","Vty","Acdf"],
"multi":[1.4,2.5,1.6,2.2]}
df=pd.DataFrame.from_dict(data)
print(df)

我试试这个:

for count1, i in enumerate(df["col1"]):
    if df.at[i, "name"].contains("Ac|Vt"):
        print("good")

我得到了那个错误

AttributeError: 'str' object has no attribute 'contains'

我怎样才能使用包含那种方式?

【问题讨论】:

  • if 'A' in df.at[i, "name"]: ?
  • 我刚刚更改了 CONTIAINS 中的条件无论如何我明白了 KeyError: 4

标签: python pandas contains


【解决方案1】:

不需要循环。

df.loc[(df.name.str.contains('Ac')|df.name.str.contains('Vt'))] 

【讨论】:

  • 我需要做循环,但我可以将它用作我的循环之前的过滤器
  • 那能回答你的问题吗?
  • 不完全是,但很有用
【解决方案2】:

你可以完全避免使用 for 循环。

为什么不直接使用df["name"].str.contains("Ac|Vt")

您也可以将结果添加为单独的列:

df.loc[df["name"].str.contains("Ac|Vt"), "status"] = "good"

【讨论】:

  • 我需要做循环,但我可以将它用作我的循环之前的过滤器
【解决方案3】:

让我们尝试使用DataFrame.iterrows

for _, j in df.iterrows():
    if "Ac" in j['name'] or "Vt" in j['name']:
        print('Good')

【讨论】:

  • 这是方向,但我仍然需要像这里一样使用“枚举”“for count1, i in enumerate(df["col1"]):”
  • 这里不需要枚举,iterrows return (index, Series)
猜你喜欢
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2021-10-04
  • 2019-12-02
  • 2021-09-25
  • 2014-03-04
相关资源
最近更新 更多