首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >熊猫:将多个范围的值转换为行

熊猫:将多个范围的值转换为行
EN

Stack Overflow用户
提问于 2020-07-15 12:58:00
回答 1查看 308关注 0票数 2

经过一些谷歌搜索,但没有任何良好的匹配,我希望您帮助我完成以下转换。我在用{FROM-TO}样式编写的值中有一些范围:

代码语言:javascript
运行
复制
df_current = pd.DataFrame.from_dict({'A': ['test{1-2}this{1-3}', 'or{2-3}'], 'B': ['yes', 'no']})

    A                   B
0   test{1-2}this{1-3}  yes
1   or{2-3}             no

为了进行进一步的处理,我想创建以下内容:

代码语言:javascript
运行
复制
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           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

注意,对于新行,B只是简单地重复。

谢谢你,勒内

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-15 13:57:04

使用:

代码语言:javascript
运行
复制
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函数,它将输入作为字符串参数,例如,'test{1-2}this{1-3}',并映射该字符串以生成所有可能的字符串,这些字符串可以通过将范围乘以相应的单词来获得。函数mapper用于输入字符串'test{1-2}this{1-3}'的工作可以进一步解释为:

代码语言:javascript
运行
复制
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:使用列A上的A来映射列A的每个值上的函数mapper

代码语言:javascript
运行
复制
# print(df)

                                                                          A    B
0  [test1this1, test1this2, test1this3, test2this1, test2this2, test2this3]  yes
1                                                                [or2, or3]   no

步骤C:使用列A上的A将每个列表(如A列中的值)转换为复制索引值的行。

代码语言:javascript
运行
复制
# 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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62915440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档