首页 > 解决方案 > 如何使用链接到关键字的数组创建字典

问题描述

所以基本上我需要创建一个字典(或其他类似的数据结构),在其中我将一个数组作为一个参数并将其映射到一个关键字。一个例子可能是如果你有一个数组

a=['Ohio','California','Colorado'] 

b=['Los Angeles','San Diego','Denver'] 

真实例子:

data['OCC_Desc'] = ['Oncology','Market_ana','67W045','Fret678',etc..]
data['LoB'] = ['7856op','Ran0p','Mkl45',etc..]

范围:

param['column_name']=['OCC_Desc','LoB','OCC',etc..]
param['parameter'] = ['Oncology','7856op','Fret678',etc...]
param['Offering'] = ['Medicine','Transport','Supplies',etc...]

如果我使用这个“字典”,输出将在这个简短的例子中

data['Offering'] = ['Medicine','Transport']

参数的数据框结构示例

  Column      Parameter     Offering
0  Location   Los Angeles    City 
1  Team       Los Angeles    Lakers
2  Location   Colorado        State
3  Food        Italy         Pizza
4  Location    Germany        Country

您将“a”链接到字符串“State”,将“b”链接到字符串“City”。所以稍后当我在数据帧上实现它时,我可以给出一个输入列,这个“字典”会将数据帧的每一行检查到这个数组中并返回“城市”或“州”。

The example above is just for understanding the problem, in reality i have to do this to a dataset for school and i have the parameters for multiple columns linking to multiple categories (14 columns that act as parameters and 16 different categories as result, which this categories can be the result from multiple parameters [literally hundreds] and from different columns)

标签: pythondictionary

解决方案


import pandas

a = ['Ohio','California','Colorado']
b = ['Los Angeles','San Diego','Denver']

param_dict = {
    'State':a,
    'City':b}

df_dict = {
    'x':['Ohio','ToothBrush','San Diego'],
    'y':['Colorado','Hammer','Denver'],
    'z':['California','Gun','Los Angeles']}

df = pandas.DataFrame(data = df_dict)
print(df) 

for index,row in df.iterrows():
    row = row[:]
    if set(param_dict.get('State')).issubset(set(row)):
        print(f"Row {list(row)} at index {index} is a State")
    if set(param_dict.get('City')).issubset(set(row)):
        print(f"Row {list(row)} at index {index} is a City")

OUTPUT

            x         y            z
0        Ohio  Colorado   California
1  ToothBrush    Hammer          Gun
2   San Diego    Denver  Los Angeles

Row ['Ohio', 'Colorado', 'California'] at index 0 is a State
Row ['San Diego', 'Denver', 'Los Angeles'] at index 2 is a City

推荐阅读