Python字符串转换,去掉空格,添加连字符

2024-06-26 13:57:27 发布

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

在pandas数据框中有一列的格式如下

f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17

我想把它转换成:

f1d3a40a-d06a-4b4a-83d4-4fc91f151117

我知道我可以用replace(" ", "")去掉空格,但是我不知道如何在我需要的地方插入连字符。你知道吗

我也不知道如何将其应用于熊猫系列对象。你知道吗

任何帮助都将不胜感激!你知道吗


Tags: 数据pandas格式地方字符replacea4f1
2条回答
a = "f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17"
c = "f1d3a40a-d06a-4b4a-83d4-4fc91f151117"
b = [4,2,2,2,6]

def space_2_hyphens(s, num_list,hyphens = "-"):
    sarr = s.split(" ")
    if len(sarr) != sum(num_list):
        raise Exception("str split num must equals sum(num_list)")
    out = []
    k = 0
    for n in num_list:
        out.append("".join(sarr[k:k + n]))
        k += n
    return hyphens.join(out)


print(a)
print(space_2_hyphens(a,b))
print(c)

这看起来像一个UUID,所以我就用这个模块

>>> import uuid
>>> s = 'f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17'
>>> uuid.UUID(''.join(s.split()))
UUID('f1d3a40a-d06a-4b4a-83d4-4fc91f151117')
>>> str(uuid.UUID(''.join(s.split())))
'f1d3a40a-d06a-4b4a-83d4-4fc91f151117'

编辑:

df = pd.DataFrame({'col':['f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17',
                          'f1 d3 a4 0a d0 6a 4b 4a 83 d4 4f c9 1f 15 11 17']})

df['col'] = df['col'].str.split().str.join('').apply(uuid.UUID)
print (df)
                                    col
0  f1d3a40a-d06a-4b4a-83d4-4fc91f151117
1  f1d3a40a-d06a-4b4a-83d4-4fc91f151117

相关问题 更多 >