gpt4 book ai didi

python - 为什么 pandas Series.str 将数字转换为 NaN?

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:21 24 4
gpt4 key购买 nike

这可能是我的根本误解,但我希望 pandas.Series.strpandas.Series 值转换为字符串。

但是,当我执行以下操作时,系列中的数值将转换为 np.nan:

df = pd.DataFrame({'a': ['foo    ', 'bar', 42]})
df = df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)
print(df)

Out:
a
0 foo
1 bar
2 NaN

如果我首先将 str 函数应用于每一列,数值将被转换为字符串而不是 np.nan:

df = pd.DataFrame({'a': ['foo    ', 'bar', 42]})
df = df.apply(lambda x: x.apply(str) if x.dtype == 'object' else x)
df = df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)
print(df)

Out:
a
0 foo
1 bar
2 42

有关此主题的文档相当少。我错过了什么?

最佳答案

在这一行中:

df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)

x.dtype 查看整个系列(列)。该列不是数字。因此,整个列都对类似的字符串进行操作。

在你的第二个例子中,数字没有被保留,它是一个字符串 '42'

输出的差异是由于panda的str和python的str不同造成的。

对于 pandas .str,这不是转换,它是一个访问器,允许您对每个元素执行 .strip()。这意味着您尝试将 .strip() 应用于整数。这会抛出异常,pandas 通过返回 Nan 来响应异常。

.apply(str) 的情况下,您实际上是将值转换为字符串。稍后当您应用 .strip() 时会成功,因为该值已经是一个字符串,因此可以被剥离。

关于python - 为什么 pandas Series.str 将数字转换为 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com