AttributeError“dataframe”对象没有属性“str”

问题描述 投票:0回答:2

我正在尝试过滤掉包含产品列表的数据框。但是,每当我运行代码时,我都会收到错误

'dataframe' object has no attribute 'str'

这是代码行:

include_clique = log_df.loc[log_df['Product'].str.contains("Product A")]

Product 是一种对象数据类型。

import pandas as pd
import numpy as np

data = pd.read_csv("FILE.csv", header = None)

headerName = ["DRID", "Product", "M24", "M23", "M22", "M21"] 
data.columns = [headerName]

log_df = np.log(1 + data[["M24", "M23", "M22", "M21"]])
copy = data[["DRID", "Product"]].copy()
log_df = copy.join(log_df)

include_clique = log_df.loc[log_df['Product'].str.contains("Product A")]

这是头部:

       ID  PRODUCT       M24       M23       M22  M21
0  123421        A  0.000000  0.000000  1.098612  0.0   
1  141840        A  0.693147  1.098612  0.000000  0.0   
2  212006        A  0.693147  0.000000  0.000000  0.0   
3  216097        A  1.098612  0.000000  0.000000  0.0   
4  219517        A  1.098612  0.693147  1.098612  0.0
python pandas dataframe indexing attributeerror
2个回答
28
投票

简短回答:

data.columns=[headerName]
更改为
data.columns=headerName

说明:当设置

data.columns=[headerName]
时,列是MultiIndex对象。因此,您的
log_df['Product']
是一个 DataFrame,并且对于 DataFrame,没有
str
属性。

当您设置

data.columns=headerName
时,您的
log_df['Product']
是单列,您可以使用
str
属性。

出于任何原因,如果您需要将数据保留为 MultiIndex 对象,还有另一个解决方案:首先将您的

log_df['Product']
转换为 Series。之后,
str
属性就可用了。

products = pd.Series(df.Product.values.flatten())
include_clique = products[products.str.contains("Product A")]

但是,我想第一个解决方案就是您正在寻找的


1
投票

当您尝试访问数据框没有的属性时,您会得到

AttributeError: 'DataFrame' object has no attribute ...

一种常见的情况是,当列名称包含空格(例如

.
)时,您尝试使用
[]
而不是
'col1 '
选择列。

df.col1       # <--- error
df['col1 ']   # <--- no error

另一个常见情况是当您尝试在 DataFrame 上调用 Series 方法时。例如,

tolist()
(或
map()
)是系列方法,因此必须在列上调用它们。如果你在 DataFrame 上调用它们,你会得到

AttributeError: 'DataFrame' object has no attribute 'tolist'

AttributeError: 'DataFrame' object has no attribute 'map'

正如 hoang tran 所解释的,OP 也发生了这种情况。

.str
是一个 Series 访问器,它没有为 DataFrame 实现。


另一种情况是,如果您有拼写错误并尝试调用/访问根本未定义的属性;例如如果你尝试调用

rows()
而不是
iterrows()
,你会得到

AttributeError: 'DataFrame' object has no attribute 'rows'

您可以使用以下理解来检查属性的完整列表。

[x for x in dir(pd.DataFrame) if not x.startswith('_')]

当您将列名称指定为

df.columns = [['col1', 'col2']]
时,
df
现在是一个 MultiIndex 数据框,因此要访问每一列,您需要传递一个元组:

df['col1'].str.contains('Product A')    # <---- error
df['col1',].str.contains('Product A')   # <---- no error; note the trailing comma

事实上,您可以传递一个元组来选择任何 MultiIndex 数据帧的一列,例如

df['level_1_colname', 'level_2_colname'].str.contains('Product A')

您还可以通过在其上映射“展平器”函数来展平 MultiIndex 列名称。常见的是

''.join
:

df.columns = df.columns.map('_'.join)
© www.soinside.com 2019 - 2024. All rights reserved.