简体   繁体   English

'str' object 在 Pandas 中没有属性 'to_string'

[英]'str' object has no attribute 'to_string' in Pandas

I have a dataframe:我有一个 dataframe:

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

I'm selecting a row and using to_string(index=False) on it.我正在选择一行并在其上使用 to_string(index=False) 。

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.我在大型 dataframe 上反复执行此操作,100 次中有 99 次没问题。 Every once in a while though, I get AttributeError: 'str' object has no attribute 'to_string' .不过,每隔一段时间,我就会得到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?这可能是什么原因造成的?

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.如果您的列名恰好是 DataFrame 本身的字符串属性的名称,我可以想到一种情况,因为您最终会在实际字符串上调用to_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?也许检查你的列名没有冲突,或者使用df['col']而不是df.col到 select 列?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM