Issue
I am trying to read .csv file into dictionary in a certain format. Below is the reproducible format for the dataframe.
# initialize list of lists
data = [['fac1', 1,11], ['fac1', 2,12], ['fac1',3,13],['fac2',1,8],['fac2',2,9],['fac2',3,20]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['facility', 'customer','distance'])
print(df)
Output
facility customer distance
fac1 1 11
fac1 2 12
fac1 3 13
fac2 1 8
fac2 2 9
fac2 3 20
I want to read this into a dictionary in certain format below
{'Fac-1': {1: 4, 2: 5, 3: 6, 4: 8, 5: 10},
'Fac-2': {1: 6, 2: 4, 3: 3, 4: 5, 5: 8},
'Fac-3': {1: 9, 2: 7, 3: 4, 4: 3, 5: 4}}
Solution
Have you tried something like this :
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=["facility", "customer", "distance"])
dict = {
k.replace("fac", "Fac_"): {c.customer: c.distance for _, c in v.iterrows()}
for k, v in df.groupby(["facility"])
}
Answered By - karim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.