从包含产品订单项(以MDX查询格式嵌入)和产品类别代码的Pandas数据框df3pa
中,我有一个词典uni3pa
,产品类别代码为Code
作为词典{ {1}},以及字符串keys
(MDX格式)作为Item
values
摘要uni3pa = df3pa.groupby('Code')['Item'].apply(list).to_dict()
:
uni3pa
我得到的最终结果是使用uni3pa =
{'3PA SMARTPAY': ['[Item].[Item].[10006543 - Smartpay User Licence]',
'[Item].[Item].[10006544 - SmartPay User Licence per Site]'],
'3PA OTHER': ['[Item].[Item].[10001234 - 3rd Party App User Licence]',
'[Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site]',
'[Item].[Item].[10001236 - 3rd Party Apps Single User]']}
连接每个key
中的所有值,以生成可以使用的MDX查询,例如:
'+'
使用this link(我使用了许多其他工具,但这是我可以找到的最有帮助的方法),我能够为每个产品分组创建数组,如下所示:
uni3pa['3PA OTHER'] = '[Item].[Item].[10001234 - 3rd Party App User
Licence] + [Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site] +
[Item].[Item].[10001236 - 3rd Party Apps Single User]'
我在这里选择了一个数组,因为这是我看到的将所有组转换为所需格式的最简单方法。但是,有100个群组,如果我能够使用群组名称(例如array = []
for el in [' + '.join(value) for key, value in uni3pa.items()]:
array.append(el)
In [46]: array[2]
Out[46]: '[Item].[Item].[10001234 - 3rd Party App User Licence] +
[Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site] +
[Item].[Item].[10001236 - 3rd Party Apps Single User]'
#for clarity, array[2] is '3PA OTHER'
而不是3PA OTHER
来标识它们,则会容易得多。
在字典中必须有一种更简单的方法来执行此操作,以便我可以调用array[2]
并且值是必需的格式?
答案 0 :(得分:0)
您可以如下图所示迭代字典的键。
for key in uni3pa.keys():
uni3pa[key] = ' + '.join(uni3pa[key])
现在这些值采用所需的格式。
答案 1 :(得分:0)
这是通过将列表理解更改为字典理解来实现的:
>>> uni3pa = {'3PA SMARTPAY': ['[Item].[Item].[10006543 - Smartpay User Licence]',
'[Item].[Item].[10006544 - SmartPay User Licence per Site]'],
'3PA OTHER': ['[Item].[Item].[10001234 - 3rd Party App User Licence]',
'[Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site]',
'[Item].[Item].[10001236 - 3rd Party Apps Single User]']}
>>> {k: ' + '.join(v) for k, v in uni3pa.items()}
{'3PA SMARTPAY': '[Item].[Item].[10006543 - Smartpay User Licence] + [Item].[Item].[10006544 - SmartPay User Licence per Site]',
'3PA OTHER': '[Item].[Item].[10001234 - 3rd Party App User Licence] + [Item].[Item].[10001235 - 3rd Party App User Licence (min 3 per site] + [Item].[Item].[10001236 - 3rd Party Apps Single User]'}