convert dataframe row to dict

Question:

I have datarame like the sample data below. I’m trying to convert one row from the dataframe in to a dict like the desired output below. But when I use to_dict I get the indice along with the column value. Does anyone know how to get convert the row to a dict like the desired output? Any tips greatly appreciated.

Sample data:

print(catStr_df[['Bottle Volume (ml)', 'Pack']][:5])

      Bottle Volume (ml)  Pack
595                  750    12
1889                 750    12
3616                1000    12
4422                 750    12
5022                 750    12


Code:

v = catStr_df[catStr_df['Item Number']==34881][['Bottle Volume (ml)', 'Pack']]
.drop_duplicates(keep='first').to_dict()

v

Output:

{'Bottle Volume (ml)': {9534: 1000}, 'Pack': {9534: 12}}

Desired output:

{'Bottle Volume (ml)': 1000, 'Pack': 12}
Asked By: user3476463

||

Answers:

Try adding .to_dict('records')[0] to the row you want

catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]
Answered By: nimrodz

taking a different tactic, this works but you need to get a list of columns. This assumed you want the index number as a dict item

def row_converter(row, listy):
    #convert pandas row to a dictionary
    #requires a list of columns and a row as a tuple
    count = 1
    pictionary = {}
    pictionary['Index'] = row[0]
    for item in listy:
        pictionary[item] = row[count]
        count += 1
    print(pictionary)
    return pictionary

df = PD.read_csv("yourFile", dtype=object, delimiter=",", na_filter=False)
listy = df.columns
for row in df.itertuples():
    rowDict = row_converter(row, listy)
Answered By: brian.the.archivist

Use df.to_dict(orient='index') to have index value as keys for easy retrieval of data

Answered By: SenthurLP
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.