我有一个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。
有一节描述了每个字符串函数,特别是我想使用的函数slice
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数据帧列上获取子字符串的正确方法来执行向量操作。
谢谢你
我想我会在str.extract中使用一些regex(您可以根据需要进行调整):
这读作:用任意两个字符(忽略)开始(
^
),接下来的三个(任何)字符是state_code
,后面跟任意字符(忽略),后面跟四个数字是area_code
。。。相关问题 更多 >
编程相关推荐