gpt4 book ai didi

python - 如何按 '/' 拆分字符串并通过数据帧中的拆分子字符串对其进行重组?

转载 作者:行者123 更新时间:2023-12-03 16:19:18 25 4
gpt4 key购买 nike

我需要根据字符 '/' 拆分单词并以这种方式改造单词:
这个数据框包含一些 child 和他们的复活节礼物。有些 child 有两件礼物,而有些 child 只有一件。

data = {'Presents':['Pink Doll / Ball', 'Bear/ Ball', 'Barbie', 'Blue Sunglasses/Airplane', 'Orange Kitchen/Car', 'Bear/Doll', 'Purple Game'],
'Kids': ['Chris', 'Jane', 'Betty', 'Harry', 'Claire', 'Sofia', 'Alex']
}

df = pd.DataFrame (data, columns = ['Presents', 'Kids'])

print (df)
这个数据框看起来像这样:
                   Presents    Kids
0 Pink Doll / Ball Chris
1 Bear/ Ball Jane
2 Barbie Betty
3 Blue Sunglasses/Airplane Harry
4 Orange Kitchen/Car Claire
5 Bear/Doll Sofia
6 Purple Game Alex
我试图划定他们的礼物,并以这种方式改造他们,保持他们相关的颜色: 'Pink Doll/Ball'将分为两部分: 'Pink Doll' , 'Pink Ball' .除此之外,同一个 child 应该与他们的礼物相关联。
颜色和礼物可以是任何东西,我们只知道 结构 是: 颜色 Present1/Present2 , 或 彩礼或只是 礼物 .所以最后应该是:
  • 用于彩色演示/演示 --> 彩色演示 1 和彩色演示 2
  • 对于彩色礼物 ---> 彩色礼物
  • 礼物 ---> 礼物

  • 所以最终的数据框应该是这样的:
               Presents    Kids
    0 Pink Doll Chris
    1 Pink Ball Chris
    2 Bear Jane
    3 Ball Jane
    4 Barbie Betty
    5 Blue Sunglasses Harry
    6 Blue Airplane Harry
    7 Orange Kitchen Claire
    8 Orange Car Claire
    9 Bear Sofia
    10 Doll Sofia
    11 Purple Game Alex
    我的第一种方法是将列转换为列表并使用列表。像这样:
    def count_total_words(string):
    total = 1
    for i in range(len(string)):
    if (string[i] == ' '):
    total = total + 1
    return total

    coloured_presents_to_remove_list = []
    index_with_slash_list = []
    first_present = ''
    second_present= ''
    index_with_slash = -1
    refactored_second_present = ''
    for coloured_present in coloured_presents_list:
    if (coloured_present.find('/') >= 0):
    index_with_slash = coloured_presents_list.index(coloured_present)
    index_with_slash_list.append(index_with_slash)
    first_present, second_present = coloured_present.split('/')
    coloured_presents_to_remove_list.append(coloured_present)
    if count_total_words(first_present) == 2:
    refactored_second_present = first_present.split(' ', 1)[0] + ' ' + second_present
    second_present = refactored_second_present
    coloured_presents_list.append(first_present)
    coloured_presents_list.append(second_present)
    kids_list.insert(coloured_presents_list.index(first_present), kids_list[index_with_slash])
    kids_list.insert(coloured_presents_list.index(second_present), kids_list[index_with_slash])

    for present in coloured_presents_to_remove_list:
    coloured_presents_list.remove(present)

    for index in index_with_slash_list:
    kids_list.pop(index)
    但是,我意识到在某些时候,我可能会错误地丢失一些索引,因此我尝试将 Pandas 用于数据帧。
    mask = df['Presents'].str.contains('/', na=False, regex=False)
    df['First Present'], df['Second Present'] = df.loc[mask, 'Presents'].split('/')

    最佳答案

    您可以使用 str.split使用 regexexpand=True得到你的第一个和第二个礼物。请注意,这将处理三种情况 'present1/present2' , 'coulour present''present' .在后两种情况下,新创建的列 'present2'将是 None .
    办案'colour present1/present2'您可以使用 str.extract使用包含允许颜色的正则表达式(参见下面的 colours_regex)。这是为了区分颜色与由两个单词组成的礼物(例如 'Barby Doll' )。
    最后一步是使用 melt'Kids'作为标识符

    df[['present1', 'present2']] = df.Presents.str.split('\s*/\s*', expand=True)
    colours_regex = '(Blue|Purple|Pink|Orange)' # maybe not ideal if there are vast amounts of colours as this needs updating for every colour
    df['colour'] = df.present1.str.extract(colours_regex)
    df.loc[df.colour.notnull()&df.present2.notnull(), 'present2'] = df.loc[df.colour.notnull()&df.present2.notnull(), ['colour', 'present2']].agg(' '.join, axis=1)
    result = df.melt(id_vars='Kids', value_vars=['present1', 'present2'], value_name='Present')
    result = result.loc[result.Present.notnull(), ['Present', 'Kids']]

    关于python - 如何按 '/' 拆分字符串并通过数据帧中的拆分子字符串对其进行重组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66889932/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com