我有一个问题困扰了我好几个小时。我需要对 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
关于Python:pandas DataFrame 中的字符串切片是一个系列?我需要它可以转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068572/