python - Pandas:将具有多个范围的值转换为行
问题描述
经过一番谷歌搜索并且没有任何好的匹配,我希望你能帮助我完成以下转换。我有一些以{FROM-TO}
样式编写的值范围:
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
为了进一步处理,我想创建这个:
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 只是重复的。
谢谢,勒内
解决方案
利用:
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}'
可以进一步解释为:
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.map
on columnA
将函数映射到column 的mapper
每个值上A
。
# print(df)
A B
0 [test1this1, test1this2, test1this3, test2this1, test2this2, test2this3] yes
1 [or2, or3] no
步骤 C:使用DataFrame.explode
列A
将每个列表(如列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
推荐阅读
- php - 使用 SQL 更新查询绑定参数
- python - 自定义的小型 CNN 比预训练的分类器具有更好的准确性
- azure - Azure Functions:如何在同一区域中的多个 Function 应用之间进行负载平衡
- python - 无法正确安装不和谐模块
- python - 基于人脸识别的考勤系统
- haproxy - HAProxy:无法在未经验证的情况下在标头中转发客户端证书
- javascript - 无条件时间四舍五入
- python - Tkinter:按钮和命令
- centos - OpenSSH sftp 'put' 在源文件夹上是否带有斜杠?
- r - 在 R 中检测其他环境中的方法——用于在 testthat 中进行测试