第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

熊貓:將具有多個(gè)范圍的值轉(zhuǎn)換為行

熊貓:將具有多個(gè)范圍的值轉(zhuǎn)換為行

尚方寶劍之說 2023-03-08 15:25:24
經(jīng)過一些谷歌搜索但沒有任何好的匹配,我希望你能幫助我完成以下轉(zhuǎn)換。我有一些以{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為了進(jìn)一步處理,我想創(chuàng)建這個(gè):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請(qǐng)注意,B 只是為新行復(fù)制。
查看完整描述

1 回答

?
不負(fù)相思意

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊

使用:


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)

細(xì)節(jié):


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


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將函數(shù)映射mapper到 column 的每個(gè)值A。


# print(df)


                                                                          A    B

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

1                                                                [or2, or3]   no

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


# 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


查看完整回答
反對(duì) 回復(fù) 2023-03-08
  • 1 回答
  • 0 關(guān)注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)