将列中的字符串拆分为多个字符串

2024-04-28 11:44:25 发布

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

很抱歉,如果这个问题已经得到了回答,但我没有找到任何答案。我想拆分&;在多个字符串中转换长字符串 我有数据帧df:

       no         strings
1.  A_12_234   gef|re1234|gef|re0943
2.  O_257363   tef|fe4545|tef|fe3333|tef|9995

我想创建单个字符串并创建新列

我得到的输出:

       no         strings                          new_col
1.  A_12_234   gef|re1234|gef|re0943                <thekeys db="gef" value="re1234"/>\n<thekeys db="gef" value="re0943"/>

2.  O_257363   tef|fe4545|tef|fe3333|tef|9995       <thekeys db="tef" value="fe4545"/>\n<thekeys db="tef" value="fe3333"/>

期望输出:

         no         strings                          new_col
1.  A_12_234   gef|re1234|gef|re0943                <thekeys db="gef" value="re1234"/>\n<thekeys db="gef" value="re0943"/>

2.  O_257363   tef|fe4545|tef|fe3333|tef|9995       <thekeys db="tef" value="fe4545"/>\n<thekeys db="tef" value="fe3333"/>\n<thekeys db="tef" value="9995"/>

我不知道我在哪里犯了错误,因为它跳过了几对

以下是代码:

def createxm(x):
try:
    parsedlist = x['strings'].split('|')
    print(parsedlist)
    cnt = len(parsedlist)/2
    print(cnt)
    xm_list = []
    for i in range(0, int(cnt), 2):
        xm_list.append('<thekeys db="{}" value="{}"/>'.format(parsedlist[i], parsedlist[i+1]))
        xm_string = '\n'.join(xml_list)
    return xm_string
except:
    return None

多谢各位


Tags: no字符串dbvaluexmstringscntgef
2条回答

你就快到了。问题出在划分cnt = len(parsedlist/2)的地方

更正代码:

def createxm(x):
    try:
        parsedlist = x['strings'].split('|')
        print(parsedlist)
        cnt = len(parsedlist)
        print(cnt)
        xm_list = []
        for i in range(0, int(cnt), 2):
            xm_list.append('<thekeys db="{}" value="{}"/>'.format(parsedlist[i], parsedlist[i+1]))
            xm_string = '\n'.join(xm_list)
        return xm_string
    except:
        return None
df['new_col'] = df.apply(lambda x:createxm(x), axis=1)

印刷品:

df.new_col.iloc[1]
'<thekeys db="tef" value="fe4545"/>\n<thekeys db="tef" value="fe3333"/>\n<thekeys db="tef" value="9995"/>'

只需拆分|上的值,然后使用前四个值获得所需的字符串,您可以使用str.format()

fString = '<thekeys db="{}" value="{}"/>\n<thekeys db={} value="{}"/>'
df['strings'].str.split('|').apply(lambda x: fString.format(x[0], x[1], x[2],  x[3]))

输出:

1.0    <thekeys db="gef" value="re1234"/>\n<thekeys d...
2.0    <thekeys db="tef" value="fe4545"/>\n<thekeys d...
Name: strings, dtype: object

相关问题 更多 >