herpderp
herpderp

Reputation: 16147

'str' object has no attribute 'to_string' in Pandas

I have a dataframe:

| column1  | column2        |
| -------- | -------------- |
| abc      | 1              |
| def      | 16             |
| ghi      | 982            |

I'm selecting a row and using to_string(index=False) on it.

something = df.loc(df['column2'] == 982]
print(something.column1.to_string(index=False))

I'm doing this repeatedly over a large dataframe and 99 times out of 100 it's fine. Every once in a while though, I get AttributeError: 'str' object has no attribute 'to_string'. There's nothing unusual about the data in the instances where this happens. What could be causing this?

Upvotes: 0

Views: 1747

Answers (1)

richard_apple_pies
richard_apple_pies

Reputation: 21

One case I can think of where this might happen if your column name happens to be the name of a string property of the DataFrame itself, since you end up calling to_string() on an actual string.

Here's an (unlikely) example to demonstrate.

df = pd.DataFrame({"col1": ['foo', 'foo', 'bar'], "_info_axis_name": [1,2,3]})
df._info_axis_name.to_string()

> AttributeError: 'str' object has no attribute 'to_string'

Perhaps check your column names are not clashing, or use df['col'] instead of df.col to select the column?

Upvotes: 2

Related Questions