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

标签 python string pandas formatting uuid

我在 pandas 数据框中有一列,其格式如下

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

我想把它转换成这样:

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

我知道我可以使用 replace("", "") 去除空格,但我不确定如何将连字符插入到我需要的确切位置。

我也不确定如何将它应用于 pandas 系列对象。

任何帮助将不胜感激!

最佳答案

这看起来像一个 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

关于Python字符串转换,去掉空格,加连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348892/

相关文章:

python - 使用Perl、Python或Ruby,如何编写一个程序到 "click"在预定的时间显示在屏幕上?

python - 我可以在手动关闭程序时让 python 做些什么吗?

python - 从 tkinter 颜色名称获取 RGB 值

c# - C#从字符串中提取十进制数

python-3.x - 如何将字节数据转换为 python pandas 数据帧?

python - 枕头 : Strange output creating RGB image from nxnx3 numpy matrix

java - 删除字符串末尾的所有标点符号

c# - 在 C# 中动态添加一个字段到集合?

python - Pandas 如何将 3 组的列旋转成行

python - 如何根据第一个特定数字和其余数字剪切字符串