【问题标题】:Python string conversion, take out spaces, add hyphensPython字符串转换,去掉空格,加连字符
【发布时间】:2019-01-24 14:26:12
【问题描述】:

我在 pandas 数据框中有一列,其格式类似于

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

我想将其转换为:

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

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

我也不确定如何将其应用于熊猫系列对象。

任何帮助将不胜感激!

【问题讨论】:

  • 是单个单元格还是整个列?还有连字符背后的逻辑是什么?
  • 整列,连字符的逻辑是从 AWS athena 下载之前的原始格式,现在我需要将此数据帧加入到原始数据(有连字符)

标签: python string pandas formatting uuid


【解决方案1】:

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

【讨论】:

  • 这绝对是我以前不知道的!不过,我在 Pandas 系列上使用它仍然有问题.... 使用:“df.col = str(uuid.UUID(''.join(df.col.str.split())))” 我得到一个类型错误“TypeError:序列项 0:预期的 str 实例,找到列表”
  • 您必须使用applystr.replacedf.col.str.split() 会给你一个Serieslists。
【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2014-08-18
    • 2021-12-12
    • 2021-05-11
    相关资源
    最近更新 更多