I have a DataFrame
which I need to loop through row-wise and then, convert each row (Series
) to a json string.
I am looping like so:
for index, row in df.iterrows():
print(row.to_json(orient='records'))
but the above is outputting values in a list (without column names)
I want to output the data in key-value pairs where the keys are the column name of that row element. How can I achieve this?
CodePudding user response:
IIUC use orient='index'
, your solution should be change:
json = {index: row.to_json(orient='index') for index, row in data.iterrows()}
Your loop:
for index, row in df.iterrows():
d = row.to_dict()
print(d)
Or better/simplier use:
#for json
json = data.to_json(orient='index')
#for dictionary
d = data.to_dict(orient='index')
CodePudding user response:
Use zip
function:
for index, row in df.iterrows():
a = dict(zip(df.columns, row.tolist()))
print(a)
zip
will combine the two lists element wise into a list of two values each. dict
will then convert it to key-value
pair where the first element in the inner list is the key and the second is the value.