Short answer: change data.columns=[headerName] into data.columns=headerName

Explanation: when you set data.columns=[headerName], the columns are MultiIndex object. Therefore, your log_df['Product'] is a DataFrame and for DataFrame, there is no str attribute.

When you set data.columns=headerName, your log_df['Product'] is a single column and you can use str attribute.

For any reason, if you need to keep your data as MultiIndex object, there is another solution: first convert your log_df['Product'] into Series. After that, str attribute is available.

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

However, I guess the first solution is what you're looking for

Answer from hoang tran on Stack Overflow
Top answer
1 of 2
28

Short answer: change data.columns=[headerName] into data.columns=headerName

Explanation: when you set data.columns=[headerName], the columns are MultiIndex object. Therefore, your log_df['Product'] is a DataFrame and for DataFrame, there is no str attribute.

When you set data.columns=headerName, your log_df['Product'] is a single column and you can use str attribute.

For any reason, if you need to keep your data as MultiIndex object, there is another solution: first convert your log_df['Product'] into Series. After that, str attribute is available.

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

However, I guess the first solution is what you're looking for

2 of 2
2

You get AttributeError: 'DataFrame' object has no attribute ... when you try to access an attribute your dataframe doesn't have.

A common case is when you try to select a column using . instead of [] when the column name contains white space (e.g. 'col1 ').

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

Another common case is when you try to call a Series method on a DataFrame. For example, tolist() (or map()) are Series methods so they must be called on a column. If you call them on a DataFrame, you'll get

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

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

As hoang tran explains, this is what is happening with OP as well. .str is a Series accessor and it's not implemented for DataFrames.


Yet another case is if you have a typo and try to call/access an attribute that's simply not defined; e.g. if you try to call rows() instead of iterrows(), you'll get

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

You can check the full list of attributes using the following comprehension.

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

When you assign column names as df.columns = [['col1', 'col2']], df is a MultiIndex dataframe now, so to access each column, you'll need to pass a tuple:

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

In fact, you can pass a tuple to select a column of any MultiIndex dataframe, e.g.

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

You can also flatten a MultiIndex column names by mapping a "flattener" function on it. A common one is ''.join:

df.columns = df.columns.map('_'.join)
🌐
Reddit
reddit.com › r/learnpython › i get the error message attributeerror: 'dataframe' object has no attribute 'str on str.split method
r/learnpython on Reddit: I get the error message AttributeError: 'DataFrame' object has no attribute 'str on str.split method
March 21, 2021 -

Hi, I'm trying to run a str.split method on a simple Pandas dataframe that has a ID column and text column that is of 'object' type and get the message AttributeError: 'DataFrame' object has no attribute 'str' . I think the column should be in a series format to run the str.split method and have tried to change the datatype to 'str', but the datatype stays a an object. How can I get the column into a series object to run a series method?

Discussions

python - 'DataFrame' object has no attribute 'str' ​ - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
pandas - Python AttributeError: 'str' object has no attribute 'DataFrame' - Stack Overflow
The following code snippet worked fine until I added a couple of lines of code that referenced date but does not append or change it above it. with the simple case of setting date = ['1/1/2001','... More on stackoverflow.com
🌐 stackoverflow.com
python - pandas - 'dataframe' object has no attribute 'str' - Stack Overflow
I am trying to filter out the dataframe that contains a list of product. However, I am getting the pandas - 'dataframe' object has no attribute 'str' error whenever I run the code. Here is the li... More on stackoverflow.com
🌐 stackoverflow.com
July 24, 2018
AttributeError: 'DataFrame' object has no attribute 'name'; Various stack overflow / github suggested fixes not working
What happened: I perform a pipeline of transformations on a Dask dataframe originating from dd.read_sql_table() from a view in an oracle DB. In one stage that follows many successful stages, I try ... More on github.com
🌐 github.com
10
January 26, 2022
🌐
Researchdatapod
researchdatapod.com › home › how to solve pandas attributeerror: ‘dataframe’ object has no attribute ‘str’
How to Solve Pandas AttributeError: 'DataFrame' object has no attribute 'str' - The Research Scientist Pod
May 14, 2022 - --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [22], in <cell line: 3>() 1 names.str.replace('Patrice', 'Ulysses') 2 print(names) ----> 3 df.str.replace('Patrice', 'Ulysses') 4 print(df) File ~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py:5583, in NDFrame.__getattr__(self, name) 5576 if ( 5577 name not in self._internal_names_set 5578 and name not in self._metadata 5579 and name not in self._accessors 5580 and self._info_axis._can_hold_identifiers_and_holds_name(name) 5581 ): 5582 return self[name] -> 5583 return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'str'
🌐
Itsourcecode
itsourcecode.com › home › attributeerror: ‘dataframe’ object has no attribute ‘str’ [solved]
attributeerror: 'dataframe' object has no attribute 'str' [Solved]
April 5, 2023 - To fix this error, we can check the data types of the DataFrame columns, convert non-string columns to strings, or use conditional statements to apply string methods only to string columns.
🌐
GitHub
github.com › dask › dask › issues › 8624
AttributeError: 'DataFrame' object has no attribute 'name'; Various stack overflow / github suggested fixes not working · Issue #8624 · dask/dask
January 26, 2022 - # Create a pandas DataFrame having the information needed to look up # the state_id, city_id, district_id, given the name of a district: self.pd_df_of_ids = self.pd.read_csv('distinct_cities_to_city_and_state_ids.csv') # self.pd_df_of_id looks like this: # district state_id city_id district_id # <object> <numpy.int8> <numpy.int64> <numpy.int64> # "Tempe, AZ, Unicersity" 2 8675309 5551212 # 'Santa Monica, CA N, Ocean ' 5 1234 5678 # ... # Define a method that takes a district as a string an returns the Dask series def find_city_and_state(self,district_str) query = "district == '{district_str}'" row = self.pd_df_of_ids.query(query) if row.shape[0] == 1: locale_info_pd_Series =\ pd.series([ row['state_id'].values[0], row['city_id'].values[0], row['district_id'].values[0] ], index=[ 'state_id', 'city_id', 'district_id']) else: locale_info_pd_series =\ pd.Series([ 0.
Author   david-thrower
Find elsewhere
🌐
Researchdatapod
researchdatapod.com › home › how to solve python attributeerror: ‘str’ object has no attribute ‘str’
How to Solve Python AttributeError: ‘str’ object has no attribute ‘str’ - The Research Scientist Pod
March 30, 2022 - To solve this error, you can use Python string methods without the str.. Alternatively, you can use the pandas.Series.str functions on the Series object, which is likely to be a column in a DataFrame.
🌐
Edureka Community
edureka.co › home › community › categories › questions › python pandas error attributeerror dataframe ...
Python Pandas error AttributeError DataFrame object has no attribute make | Edureka Community
May 1, 2020 - i was trying to print unique values in my data %matplotlib inline import pandas as pd import ... : 'DataFrame' object has no attribute 'Make'
🌐
Quora
quora.com › How-do-you-resolve-attributeerror-str-object-has-no-attribute-variables-Python-solutions
How to resolve 'attributeerror: 'str' object has no attribute 'variables'' (Python, solutions) - Quora
Fix the source of the string—load, instantiate, or look up the actual object—and avoid name shadowing so .variables is called on the correct type. ... RelatedHow do you resolve "attributeerror: 'dataframe' object has no attribute 'reshape'" (Python, Python 3.x, machine learning, deep learning, ...
🌐
Nextstrain
discussion.nextstrain.org › t › pandas-error-during-augur-filter-nonetype-object-has-no-attribute-str › 1420
Pandas error during augur filter: 'NoneType' object has no attribute 'str' - Nextstrain Discussion
August 10, 2023 - Hi, I get this error when running augur filter, and I’m not quite sure how to investigate the problem. I run this build every week with Gisaid data, so I suspect there might be some strange strain names or something? […
🌐
HatchJS
hatchjs.com › home › dataframe object has no attribute ‘str’: what it means and how to fix it
DataFrame Object Has No Attribute 'str': What It Means and How to Fix It
January 5, 2024 - Why Do I Get the Error “DataFrame Object Has No Attribute ‘str'”? The error “dataframe object has no attribute ‘str'” occurs when you try to access an attribute that does not exist on a DataFrame.
🌐
Stack Overflow
stackoverflow.com › questions › 65316249 › python-pandas-attributeerror-dataframe-object-has-no-attribute-str
Python Pandas: AttributeError: 'DataFrame' object has no attribute 'str' - Stack Overflow
Using Python Pandas and importing an Excel document, the following code is kicking back an error: df['City'] = df['City'].astype(str) df['Rent'] = np.where((df['City'].str.contains('ST PETERSBURG')) & (df['BedroomsTotal'] == 2), df['Rent'], df['LivingArea'] * df['Multiplier']) The mentioned error is: AttributeError: 'DataFrame' object has no attribute 'str' I added the top line to set the column to type string.
Top answer
1 of 2
9

First problem shoud be duplicated columns names, so after select colB get not Series, but DataFrame:

df = pd.DataFrame([['Example: s', 'as', 2], ['dd', 'aaa', 3]], columns=['colB','colB','colC'])
print (df)
         colB colB  colC
0  Example: s   as     2
1          dd  aaa     3

print (df['colB'])
         colB colB
0  Example: s   as
1          dd  aaa

#print (df['colB'].str.contains('Example:'))
#>AttributeError: 'DataFrame' object has no attribute 'str'

Solution should be join columns together:

print (df['colB'].apply(' '.join, axis=1))
0    Example: s as
1           dd aaa

df['colB'] = df.pop('colB').apply(' '.join, axis=1)
df = df[~df['colB'].str.contains('Example:')] 
print (df)
   colC    colB
1     3  dd aaa

Second problem should be hidden MultiIndex:

df = pd.DataFrame([['Example: s', 'as', 2], ['dd', 'aaa', 3]], columns=['colA','colB','colC'])
df.columns = pd.MultiIndex.from_arrays([df.columns])
print (df)
         colA colB colC
0  Example: s   as    2
1          dd  aaa    3

print (df['colB'])
  colB
0   as
1  aaa

#print (df['colB'].str.contains('Example:'))
#>AttributeError: 'DataFrame' object has no attribute 'str'

Solution is reassign first level:

df.columns = df.columns.get_level_values(0)
df = df[~df['colB'].str.contains('Example:')] 
print (df)
         colA colB  colC
0  Example: s   as     2
1          dd  aaa     3

And third should be MultiIndex:

df = pd.DataFrame([['Example: s', 'as', 2], ['dd', 'aaa', 3]], columns=['colA','colB','colC'])
df.columns = pd.MultiIndex.from_product([df.columns, ['a']])
print (df)
         colA colB colC
            a    a    a
0  Example: s   as    2
1          dd  aaa    3

print (df['colB'])
     a
0   as
1  aaa

print (df.columns)
MultiIndex(levels=[['colA', 'colB', 'colC'], ['a']],
           codes=[[0, 1, 2], [0, 0, 0]])

#print (df['colB'].str.contains('Example:'))
#>AttributeError: 'DataFrame' object has no attribute 'str'

Solution is select MultiIndex by tuple:

df1 = df[~df[('colB', 'a')].str.contains('Example:')] 
print (df1)
         colA colB colC
            a    a    a
0  Example: s   as    2
1          dd  aaa    3

Or reassign back:

df.columns = df.columns.get_level_values(0)
df2 = df[~df['colB'].str.contains('Example:')] 
print (df2)
         colA colB  colC
0  Example: s   as     2
1          dd  aaa     3

Or remove second level:

df.columns = df.columns.droplevel(1)
df2 = df[~df['colB'].str.contains('Example:')] 
print (df2)
         colA colB  colC
0  Example: s   as     2
1          dd  aaa     3
2 of 2
0

Try this:

df[[~df.iloc[i,:].str.contains('String_to_match').any() for i in range(0,len(df))]]

🌐
Sling Academy
slingacademy.com › article › pandas-attributeerror-str-object-no-attribute-str
Pandas AttributeError: ‘str’ object has no attribute ‘str’ - Sling Academy
A common error encountered is the AttributeError: 'str' object has no attribute 'str'. This tutorial will delve into the reasons behind this error and provide efficient solutions. The error occurs when you attempt to use the .str accessor on a Pandas Series object expecting it to contain strings, but the object is actually a regular string or it’s applied incorrectly. The .str accessor is powerful for vectorized string operations, but it’s only applicable to Series or DataFrames columns of dtype ‘object’ or specifically ‘string’.
🌐
CSDN
devpress.csdn.net › python › 63045ca47e6682346619a86b.html
pandas - 'dataframe' object has no attribute 'str'_python_Mangs-Python
August 23, 2022 - Explanation: when you set data.columns=[headerName], the columns are MultiIndex object. Therefore, your log_df['Product'] is a DataFrame and for DataFrame, there is no str attribute.