繁体   English   中英

Python:pandas DataFrame 中的字符串切片是一个系列? 我需要它可以转换为 int

[英]Python: String slice in pandas DataFrame is a series? I need it to be convertible to int

我有一个问题困扰了我好几个小时。 我需要在 Pandas DataFrame 中切片一个字符串变量并提取一个数值(以便我可以执行合并)。 (作为提供上下文的一种方式,变量是 .groupby 的结果......现在我正在尝试合并其他信息。

从字符串中获取数字应该很容易。

基本上,我正在做以下事情:

string = x_1 
number = string[2:]
number == 2
et voila! 

为了这个目标,让我们构建代码

In [32]: import pandas as pd
    ...: d = {'id' : [1, 2, 3, 4],
    ...:     'str_id' : ['x_2', 'x_4', 'x_8', 'x_1']}
    ...: 

In [33]: df= pd.DataFrame(d)

In [34]: df.head()
Out[34]: 
   id str_id
0   1    x_2
1   2    x_4
2   3    x_8
3   4    x_1

In [35]: df['num_id']=df.str_id.str[2:]

In [36]: df.head()
Out[36]: 
   id str_id num_id
0   1    x_2      2
1   2    x_4      4
2   3    x_8      8
3   4    p_1      1

In [37]: df.dtypes
Out[37]: 
id         int64
str_id    object
num_id    object
dtype: object

结果看起来不错——我们有一个对象,所以我们只需转换为 int 并成为黄金,对吧? 可惜没有那么多。

In [38]: df['num_id3'] = int(df['num_id'])
Traceback (most recent call last):

  File "<ipython-input-38-50312cced30b>", line 1, in <module>
    df['num_id3'] = int(df['num_id'])

  File "/Users/igor/anaconda/lib/python2.7/site-packages/pandas/core/series.py", line 92, in wrapper
    "{0}".format(str(converter)))

TypeError: cannot convert the series to <type 'int'>

好的,让我们尝试一些更简单的事情 --- 去除前导和尾随空白

 In [39]: df['num_id3'] = (df['num_id']).strip()
Traceback (most recent call last):

  File "<ipython-input-39-0af6d5f8bb8c>", line 1, in <module>
    df['num_id3'] = (df['num_id']).strip()

  File "/Users/igor/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 2744, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: 'Series' object has no attribute 'strip'

所以..不知何故我有一个系列对象......里面只有一个项目......我无法将系列对象转换为任何可用的东西

请问你会帮忙吗?! 谢谢!

您不能使用int(Series)构造(它类似于int(['1','2','3']) ,这也不起作用),您应该使用Series.astype(int)或更好pd.to_numeric(Series)代替:

In [32]: df
Out[32]:
   id str_id
0   1    x_2
1   2    x_4
2   3    x_8
3   4    x_1
4   5  x_AAA

In [33]: df['num_id'] = pd.to_numeric(df.str_id.str.extract(r'_(\d+)', expand=False))

In [34]: df
Out[34]:
   id str_id  num_id
0   1    x_2     2.0
1   2    x_4     4.0
2   3    x_8     8.0
3   4    x_1     1.0
4   5  x_AAA     NaN

暂无
暂无

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

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