Can only use str accessor with string values

Can only use str accessor with string values

1

Exception Class:

AttributeError

Raise code

values = getattr(data, "values", data)  # Series / Index
        values = getattr(values, "categories", values)  # categorical / normal

        inferred_dtype = lib.infer_dtype(values, skipna=True)

        if inferred_dtype not in allowed_types:
            raise AttributeError("Can only use .str accessor with string values!")
        return inferred_dtype

    def __getitem__(self, key):
        result = self._data.array._str_getitem(key)
        return self._wrap_result(result)

    def __iter__(self):

😲 Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

2

This error is raised when the str attribute is called on a pandas column with a non string data type. The str accessor works only on columns whose data is a string type.

Here is how to reproduce the exception.

  • Setup your virtual environment

Install pipenv

$ pip install --user pipenv  
$ mkdir testEnv
$ cd testEnv
$ pipenv install pandas
$ pipenv shell

Then run the following code inside the virtual environment.

import pandas as pd
d = {'name': ['apple', 'orange'], 'price': [1.3, 1.4]}
df = pd.DataFrame(data=d)
print(df)
# We want to remove the decimal point (.).
new_series = df['price'].str.replace('.','')
new_df = pd.DataFrame(new_series,columns=["name","price"])
new_df["name"] = df["name"]
print("\n\n",new_df)

The error message

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-f53fc8122c19> in <module>()  
4 print(df)  
5 # We want to remove the decimal point (.). 
----> 6 new_series = df['price'].str.replace('.','')  
7 new_df = pd.DataFrame(new_series,columns=["name","price"])  
8 print("\n\n",new_df) 
.
.
.
/usr/local/lib/python3.7/dist-packages/pandas/core/strings.py in _validate(data)  2155   2156 if inferred_dtype not in allowed_types: -> 2157 raise AttributeError("Can only use .str accessor with string values!")  2158 return inferred_dtype  2159  
AttributeError: Can only use .str accessor with string values!

Fixed version of the code:

To avoid raising this exception or to fix this scenario use the following code instead.

Notice the line new_series =df['price'].apply(str).str.replace('.','')

That is the solution.

import pandas as pd
d = {'name': ['apple', 'orange'], 'price': [1.3, 1.4]}
df = pd.DataFrame(data=d)
print(df)
# We want to remove the decimal point (.).
new_series =df['price'].apply(str).str.replace('.','')
new_df = pd.DataFrame(new_series,columns=["name","price"])
new_df["name"] = df["name"]
print("\n\n",new_df)
  name  price 
0 apple 1.3 
1 orange 1.4 

  name   price
0 apple    13
1 orange   14

Jan 14, 2022

Can only use str accessor with string values

Please authorize to post comment 

Add a possible fix

Please authorize to post fix

Python AttributeError: Can only use .str accessor with string values

Questions : Python AttributeError: Can only use .str accessor with string values

2022-09-26T22:41:41+00:00 2022-09-26T22:41:41+00:00

938

flights['Duration']=flights['Duration'].str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)

However I am getting this error message:

AttributeError                            Traceback (most recent call last)
    <ipython-input-24-45eafc3e9d23> in <module>()
    ----> 1 travel['Duration']=travel['Duration'].str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)
          2 
    3 frames
    /usr/local/lib/python3.6/dist-packages/pandas/core/strings.py in _validate(data)
       1965 
       1966         if inferred_dtype not in allowed_types:
    -> 1967             raise AttributeError("Can only use .str accessor with string " "values!")
       1968         return inferred_dtype
       1969 

    AttributeError: Can only use .str accessor with string values!

Total Answers 3

25

Answers 1 : of Python AttributeError: Can only use .str accessor with string values

Looks like your flights[ 'Duration'] anycodings_pandas column have not string value (probably anycodings_pandas its int64 or float64).

import pandas as pd
df = pd.DataFrame(data=[(1, '12h 50m'), (2, '1h 12m')], columns=['id', 'Duration'])
df['Duration']=df['Duration'].str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)

Result:

   id  Duration
0   1       770
1   2        72

This is works well because when we anycodings_pandas create a dataframe - second column anycodings_pandas values was string type. If we have anycodings_pandas non-consistency in base data so we anycodings_pandas should be careful with results, It can anycodings_pandas be misleading. Example:

df = pd.DataFrame(data=[(1, 123), (2, 0.123), (3, '12h 30m')], columns=['id', 'Duration'])
df['Duration']=df['Duration'].astype(str).str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)

Result:

   id  Duration
0   1   123.000
1   2     0.123
2   3   750.000

In this example we used .astype(str), anycodings_pandas but as we see If data have various anycodings_pandas datatypes - result may be really wrong. anycodings_pandas So check your datasource for dataframe anycodings_pandas and then try transform data again :)

0

2022-09-26T22:41:41+00:00 2022-09-26T22:41:41+00:00Answer Link

mRahman

5

Answers 2 : of Python AttributeError: Can only use .str accessor with string values

What you probably want to do is more anycodings_pandas like:

flights['Duration'] = pd.to_timedelta(flights['Duration']).seconds//60

which will directly convert the time anycodings_pandas string to minutes

The method you're trying to use, with anycodings_pandas apply(eval) seems . . . very unsafe.

0

2022-09-26T22:41:41+00:00 2022-09-26T22:41:41+00:00Answer Link

joy

3

Answers 3 : of Python AttributeError: Can only use .str accessor with string values

You should first cast string to the anycodings_pandas column, using astype(str).

0

2022-09-26T22:41:41+00:00 2022-09-26T22:41:41+00:00Answer Link

miraj

Can only use string accessor with string values?

One error you may encounter when using Python is: AttributeError: Can only use . str accessor with string values! This error usually occurs when you attempt to replace a pattern in a string column of a pandas DataFrame, but the column you're working with isn't actually a string.

Is Dtype object a string?

Moreover, having dtype as Object will make it less clear to work with just text and exclude the non-text values. With the new String dtype, the values are explicitly treated as strings.