TisButaScratch
TisButaScratch

Reputation: 173

iterate over rows then columns to build ColHeader:ColValue string python

I have a dataframe of distinct values, I need to iterate over each row to build a string of the column names and values in the following format:

{col1Name:row1Value
 col2Name:row1Value
 col3Name:row1Value},
{col1Name:row2Value
 col2Name:row2Value
 col3Name:row2Value},....

This needs to be dynamic so it can be applied no matter how many columns there are in the dataframe.

I have managed to iterate through the rows then columns, but not sure now how to build the string.

for index, row in distinct_features.iterrows():
    for index, column in row.iteritems():
        print(column)

Here is a sample of the dataframe:

  label hoverBackgroundColor backgroundColor
0    AF                 #FFF            #000
1    FR                 #ASD            #000
2    IT                 #DJH            #000
3    MC                 #NHG            #000
4    PA                 #GYA            #000
5    RP                 #BBH            #000
6    WT                 #ERT            #000

Upvotes: 0

Views: 44

Answers (2)

TisButaScratch
TisButaScratch

Reputation: 173

You can do it like this:

 df_dict = distinct_features.to_dict('records')

Upvotes: 1

vlemaistre
vlemaistre

Reputation: 3331

Here is a way to do it :

columns = df.columns
labels = df.label
hover = df.hoverBackgroundColor
background = df.backgroundColor

s = ''
for row in range(len(labels)):
    s += "{{{} : {} \n {} : {}\n {} : {} }}\n".format(columns[0],
                                                 labels[row], columns[1], hover[row], columns[2], background[row])

Output with the data sample you gave :

{label : AF 
 hoverBackgroundColor : #FFF
 backgroundColor : #000} 
{label : FR 
 hoverBackgroundColor : #ASD
 backgroundColor : #000} 
{label : IT 
 hoverBackgroundColor : #DJH
 backgroundColor : #000} 
{label : MC 
[...]
{label : WT 
 hoverBackgroundColor : #ERT
 backgroundColor : #000} 

Upvotes: 1

Related Questions