简体   繁体   中英

How can I convert a pandas DataFrame to Python Dictionary with only values and without columns?

I want to convert below DataFrame to Python Dictionary.

Input:

pandas.DataFrame({"Customer":["C1","C1","C2","C2], "Material":["M1","M2","M3","M3"], "Supplier":["S1","S2","S3","S4"]})

The DataFrame will look like:

  Customer  Material  Supplier
0   C1         M1       S1
1   C1         M2       S2
2   C2         M3       S3
3   C2         M3       S4

​ The output dictionary should look like:

{"C1": {"M1":["S1"], "M2":["S2"]}, "C2":{"M3":["S3","S4"]}}

Thanks in Advance for helping..!

Convert DataFrame to MultiIndex Series and then use dictionary comprehension:

s = df.groupby(['Customer','Material'])['Supplier'].apply(list)

d = {l: s.xs(l).to_dict() for l in s.index.levels[0]}
print (d)
{'C1': {'M1': ['S1'], 'M2': ['S2']}, 'C2': {'M3': ['S3', 'S4']}}
import pandas
df = pandas.DataFrame({
    "Customer": ["C1","C1","C2","C2"],
    "Material":["M1","M2","M3","M3"],
    "Supplier":["S1","S2","S3","S4"]
})
gp  = df.groupby(['Customer','Material'])["Supplier"]
result = {}
for a,b in gp:
    cust = a[0] # a - ('C1','M1')
    mat = a[1]
    if cust in result: # if cust is already in result dict, append mat
        result[cust] = {
            **result[cust],
            mat: list(b) # b is a series, so we need to convert that into list
        }
    else: # otherwise, create new cust
        result[cust] = {
            mat: list(b)
        }

print(result)

Output:

{'C1': {'M1': ['S1'], 'M2': ['S2']}, 'C2': {'M3': ['S3', 'S4']}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM