Python:如何在包含列表列表的字典中查找索引

时间:2019-12-29 07:54:57

标签: python pandas dataframe dictionary

我正在读取一个文件(三列),然后填充一个包含三个键的字典:appversiondomains

文件的示例内容为:

app            version    domain
---            ---        ---
com.easytaxi   1.1        google.com
com.easytaxi   1.1        facebook.com
com.easytaxi   1.1        google.com
com.easytaxi   1.2        google.com
com.airbnb     1.1        facebook.com
com.airbnb     1.1        facebook.com

我想在dict中存储文件的内容,以便为每个应用程序版本对存储唯一域的列表。输出字典应包含以下项目:

dict_data = {'app':['com.easytaxi','com.easytaxi','com.airbnb'],
            'version':[1.1,1.2,1.1],
            'domains':[['google.com','facebook.com'],['google.com'],['facebook.com']]} 

到目前为止,我已经尝试了以下方法:

import pandas as pd
from io import StringIO

data = StringIO(u'''app,version,domain
com.easytaxi,1.1,google.com
com.easytaxi,1.1,facebook.com
com.easytaxi,1.1,google.com
com.easytaxi,1.2,google.com
com.airbnb,1.1,facebook.com
com.airbnb,1.1,facebook.com''')

df = pd.read_csv(data)
dict_data = {'app':[],'version':[],'domains':[[]]}

for index,row in df.iterrows():  # iterating each row of df
    # need to fix this
    if row['app'] in dict_data['app'] & row['version'] in dict_data['version']:
        if row['domain'] not in dict_data['domains']:
            # then append row['domain'] to dict_data['domains'] on the correct index

1 个答案:

答案 0 :(得分:4)

你可以

import pandas as pd
from io import StringIO

data = StringIO(u'''app,version,domain
com.easytaxi,1.1,google.com
com.easytaxi,1.1,facebook.com
com.easytaxi,1.1,google.com
com.easytaxi,1.2,google.com
com.airbnb,1.1,facebook.com
com.airbnb,1.1,facebook.com''')

df = pd.read_csv(data)

df = df.drop_duplicates()
df.groupby(["app", "version"]).agg(list).reset_index().sort_values(
    "app", ascending=False
).to_dict("list")

这会给你

{'app': ['com.easytaxi', 'com.easytaxi', 'com.airbnb'],
 'version': [1.1, 1.2, 1.1],
 'domain': [['google.com', 'facebook.com'], ['google.com'], ['facebook.com']]}