亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

熊貓:將具有多個范圍的值轉換為行

熊貓:將具有多個范圍的值轉換為行

尚方寶劍之說 2023-03-08 15:25:24
經過一些谷歌搜索但沒有任何好的匹配,我希望你能幫助我完成以下轉換。我有一些以{FROM-TO}樣式編寫的值的范圍:df_current = pd.DataFrame.from_dict({'A': ['test{1-2}this{1-3}', 'or{2-3}'], 'B': ['yes', 'no']})    A                   B0   test{1-2}this{1-3}  yes1   or{2-3}             no為了進一步處理,我想創建這個:df_wish  = pd.DataFrame.from_dict({ \    'A': [\        'test1this1', 'test1this2', 'test1this3',\        'test2this1', 'test2this2', 'test2this3', \        'or2', 'or3'],    'B': [ \        'yes', 'yes', 'yes', 'yes', 'yes', 'yes', \        'no', 'no']})    A           B0   test1this1  yes1   test1this2  yes2   test1this3  yes3   test2this1  yes4   test2this2  yes5   test2this3  yes6   or2         no7   or3         no請注意,B 只是為新行復制。
查看完整描述

1 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

使用:


import re

from itertools import product


def mapper(s):

    lst = re.findall(r'(\w+)\{(\d+)-(\d+)\}', s)

    prd = [['{}{}'.format(*p) for p in product([w], range(int(m), int(n) + 1))] for w, m, n in lst]

    return list(map(''.join, product(*prd)))


df['A'] = df['A'].map(mapper)

df = df.explode('A').reset_index(drop=True)

細節:


步驟 A:定義一個mapper函數,它將輸入作為字符串參數 eg'test{1-2}this{1-3}'并映射此字符串以生成所有可能的字符串,這些字符串可以通過將范圍與相應的單詞相乘獲得。mapper輸入字符串的函數工作'test{1-2}this{1-3}'可以進一步解釋為:


print(lst) # Use 're.findall' to parse all the words and their corresponding ranges

[('test', '1', '2'), ('this', '1', '3')]


print(prd) # Use 'itertools.product' to get all inner level products

[['test1', 'test2'], ['this1', 'this2', 'this3']]


# Again use 'itertools.product' to get all outer level products

['test1this1', 'test1this2', 'test1this3', 'test2this1', 'test2this2', 'test2this3']

步驟 B:使用Series.mapon columnA將函數映射mapper到 column 的每個值A


# print(df)


                                                                          A    B

0  [test1this1, test1this2, test1this3, test2this1, test2this2, test2this3]  yes

1                                                                [or2, or3]   no

步驟 C:使用DataFrame.explodeA將每個列表(如列中的值)轉換A為復制索引值的行。


# print(df)

            A    B

0  test1this1  yes

1  test1this2  yes

2  test1this3  yes

3  test2this1  yes

4  test2this2  yes

5  test2this3  yes

6         or2   no

7         or3   no


查看完整回答
反對 回復 2023-03-08
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號