子字符串python pandas

2024-05-19 09:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,其中有一个字符串列。框架的长度超过200万行,循环提取我需要的元素是一个糟糕的选择。我当前的代码如下

for i in range(len(table["series_id"])):
    table["state_code"] = table["series_id"][i][2:4]
    table["area_code"] = table["series_id"][i][5:9]
    table["supersector_code"] = table["series_id"][i][11:12]

其中“series_id”是包含多个信息字段的字符串,我要创建一个示例数据元素:

列:

 [series_id, year, month, value, footnotes]

数据:

[['SMS01000000000000001' '2006' 'M01' 1966.5 '']
 ['SMS01000000000000001' '2006' 'M02' 1970.4 '']
 ['SMS01000000000000001' '2006' 'M03' 1976.6 '']

然而,这个系列是我正在努力的兴趣所在。我已经研究了python的str.FUNCTION,特别是pandas。

http://pandas.pydata.org/pandas-docs/stable/basics.html#testing-for-strings-that-match-or-contain-a-pattern

有一节描述了每个字符串函数,特别是我想使用的函数sliceget&;em>。理想情况下,我可以设想这样的解决方案:

table["state_code"] = table["series_id"].str.get(1:3)

或者

table["state_code"] = table["series_id"].str.slice(1:3)

或者

table["state_code"] = table["series_id"].str.slice([1:3])

当我尝试了以下函数后,得到的语法无效。

但是,唉,我似乎无法找到在pandas数据帧列上获取子字符串的正确方法来执行向量操作。

谢谢你


Tags: 数据函数字符串id元素pandasforget
1条回答
网友
1楼 · 发布于 2024-05-19 09:48:45

我想我会在str.extract中使用一些regex(您可以根据需要进行调整):

In [11]: s = pd.Series(["SMU78000009092000001"])

In [12]: s.str.extract('^.{2}(?P<state_code>.{3}).{1}(?P<area_code>\d{4}).{2}(?P<supersector_code>.{2})')
Out[12]: 
  state_code area_code supersector_code
0        U78      0000               92

这读作:用任意两个字符(忽略)开始(^),接下来的三个(任何)字符是state_code,后面跟任意字符(忽略),后面跟四个数字是area_code。。。

相关问题 更多 >

    热门问题