【问题标题】:Why does pandas string series return NaN for len() function?为什么熊猫字符串系列为 len() 函数返回 NaN?
【发布时间】:2017-11-07 16:05:11
【问题描述】:

我正在使用 Pandas 中的功耗数据集,其中包含邮政编码作为一列,但该列的数据类型是原始 CSV 文件中的整数。我想将此列更改为字符串/对象数据类型,这是我到目前为止所做的:

df = pd.read_csv('...kWh_consumption_by_ZIP.csv')
df.head()

生成的数据帧头如下所示:

如上所述,当我检查df.dtypes 时,我看到 ZIP 被列为 int64 数据类型,因此我运行以下代码来覆盖现有系列并将其更改为 object 数据类型:

df['ZIP'] = df.ZIP.astype(object)

当我查看df.ZIP 系列时,一切看起来都不错(至少肉眼看起来不错):

但是当我使用 len 函数检查系列中每一行的长度时:

df.ZIP.str.len()

...结果系列只为每一行返回 NaN(见下面的屏幕截图)。

有人知道为什么会这样吗?提前感谢您的帮助。

【问题讨论】:

  • df.ZIP.astype(str).str.len()
  • 所以我需要将 ZIP 系列转换为 str 而不是对象?我以为对象和字符串是一回事?
  • @Will 请看我对“为什么”的回答。
  • @你能查到cold的答案吗
  • 知道了。谢谢,@Wen。

标签: python string pandas


【解决方案1】:

TL;DR

您有一列整数,而转换为对象并没有解决您的问题。相反,将类型转换为str,你应该会很好。

df.ZIP.astype(str).str.len()

出于某种原因,pandas 支持 object 列上的 str 访问器。因为object 列可以包含任何对象,pandas 不做任何假设。如果对象是字符串或任何有效容器,则返回有效结果。否则,NaN

这是一个例子:

x = [{'a': 1}, 'abcde', None, 123, 45, [1, 2, 3, 4]]
y = pd.Series(x)

y

0        {'a': 1}
1           abcde
2            None
3             123
4              45
5    [1, 2, 3, 4]
dtype: object

y.str.len()
Out[741]: 
0    1.0
1    5.0
2    NaN
3    NaN
4    NaN
5    4.0
dtype: float64

对比:

y = pd.Series([1, 2, 3, 4, 5])
y

0    1
1    2
2    3
3    4
4    5
dtype: int64

y.dtype
dtype('int64')

y.str.len()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-744-acc1c109a4a4> in <module>()
----> 1 y.str.len()

y.astype(object).str.len()

0   NaN
1   NaN
2   NaN
3   NaN
4   NaN
dtype: float64

【讨论】:

  • 你头上的一朵花,@Coldspeed。
  • 这太棒了,刚刚用这个标记了一个重复项:)
  • @Vaishali 乐于提供帮助 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 2018-11-01
  • 2019-12-11
  • 2020-07-06
  • 2022-10-25
  • 2011-02-17
相关资源
最近更新 更多