0

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?

2
  • No idea - I can't reproduce when running your code in a loop 10k times. Commented Dec 20, 2021 at 2:04
  • 1
    But, I do recommend you do something.column1.iloc[0] instead of something.column1.to_string(index=False) Commented Dec 20, 2021 at 2:05

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.