简体   繁体   English

str(x) 和 x.str 有什么区别?

[英]What is the difference between str(x) and x.str?

What I needed to happen:我需要发生的事情:

Get all commas in a Pandas DataFrame replaced with dots.将 Pandas DataFrame 中的所有逗号替换为点。

What I tried to do:我试图做的事情:

df.apply(lambda x: str(x).replace(",", "."))

When I tried this, I got an error:当我尝试这个时,我得到了一个错误:

ValueError: Must have equal len keys and value when setting with an iterable. ValueError:使用可迭代设置时必须具有相等的 len 键和值。

What was the correct answer:正确答案是什么:

(found on StackOverflow) (在 StackOverflow 上找到)

df.apply(lambda x: x.str.replace(",", "."))

My question:我的问题:

What is the difference between str(x) and x.str, and why only one of them worked? str(x) 和 x.str 有什么区别,为什么只有一个有效?

pandas.Series.str (the.str.) gives you a series that it works on each column pandas.Series.str (the.str.) 为您提供适用于每一列的系列

pandas.DataFrame.apply works on columns or rows. pandas.DataFrame.apply适用于列或行。 by default row (axis{0 or 'index', 1 or 'columns'}, default 0).默认行(axis{0 或 'index',1 或 'columns'},默认 0)。

The difference is that str(x) is operating on the index of the dataframe, as apply operates on the axis=0 by default, and the .str.不同之处在于str(x)在 dataframe 的索引上运行,因为apply默认在 axis=0 上运行,而.str. is returning a series正在返回一个系列

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

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