0

I am using pandas to read any CSV files and then insert the rows into a database. I will be doing this with SQLAlchemy.

I will not know the header names or size, so it has to be dynamic. Assume the database rules will ensure data validity.

I am trying to map the column header to each data value. See below my current dataframe:

  Example 1 Example 2 Example 3 Example 4
        Cat       Dog     Mouse     Horse
        Cow       Ant       Pig  Elephant

Here is my desired outputted list:

Example 1=Cat, Example 2=Dog, Example 3=Mouse, Example 4=Horse
Example 1=Cow, Example 2=Ant, Example 3=Pig, Example 4=Elephant

I have tried using zip and iterrows with the below code:

    for index, data in df.iterrows():
        mylist.append(data.values)

    myzip = zip(columns, mylist)

    for z in myzip:
        print(z)

but this is producing one column header per multiple values as seen below:

('Example 1', array(['Cat', 'Dog', 'Mouse', 'Horse'], dtype=object))
('Example 2', array(['Cow', 'Ant', 'Pig', 'Elephant'], dtype=object))

Any help would be greatly appreciated as not sure what function I need to use. I'm aware of to_sql but I need to create an insert statement per row. Thanks

2
  • 2
    df.to_dict(orient='records') will help you. In addition, SQLAlchemy support pandas insert. Commented Apr 10, 2019 at 8:44
  • Amazing thank you very much for your help Commented Apr 10, 2019 at 9:34

1 Answer 1

1

@giser_yugang hits the ideal solution. Pandas has inbuilt method DataFrame.to_dict(orient='dict') which converts the dataframe and returns a dictionary, where the key-value pair can be customized using the parameter orient.
'records' amongst the 'orient' gives the kind of result you want.

So your dataframe:

dataframe

After using:

df.to_dict(orient='records')

gives:

[{'Example 1': 'Cat',
  'Example 2': 'Dog',
  'Example 3': 'Mouse',
  'Example 4': 'Horse'},
 {'Example 1': 'Cow',
  'Example 2': 'Ant',
  'Example 3': 'Pig',
  'Example 4': 'Elephant'}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.