在pandas中,将字符串中连字符分隔的数字展开到一个范围内

2024-05-16 09:58:51 发布

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

我有一个pandas数据框,其中邮政编码的开头按地区区分,格式如下:

region A 385
region B 656 - 659

我需要打开破折号数据:

^{pr2}$

我的代码

postcodes.iloc[:,1] = postcodes.iloc[:,1].apply(lambda x: x.split('—'))
def unwrap_codes(row):
row = row['Postcode begins with']
if len(row) > 1:
    for x, y in row:
        while x != y:
            row.append(x=+1)
postcodes['Unwraped'] = postcodes.apply(unwrap_codes, axis=1)

返回ValueError:('要解包的值太多(应为2)' 你能帮我处理这个错误吗?在


Tags: 数据pandas格式region地区codes区分row
2条回答

@cᴏʟᴅsᴘᴇᴅ的回答很好。我只是觉得无聊,想写点东西。在

idx = pd.MultiIndex.from_product([df.index, [0, 1]], names=[None, 'match'])
d = df.postcode.str.extractall('(\d+)').reindex(idx).ffill().astype(int)[0]

d.unstack().add([0, 1]).apply(lambda x: list(range(*x)), 1)

0                   [385]
1    [656, 657, 658, 659]
dtype: object

一个str.split后跟一个apply似乎可以做到:

print(df)
     region   postcode
0  region A        385
1  region B  656 - 659

df['Unwrapped'] = df.postcode.str.split('\s*-\s*')\
             .apply(lambda x: range(int(x[0]), int(x[-1]) + 1))
print(df['Unwrapped'])
0                   (385)
1    (656, 657, 658, 659)
Name: Unwrapped, dtype: object

相关问题 更多 >