Sunday, 20 April 2025

Getting Query Result from Python Dataframe

The error you're encountering is because Specresult is a CursorResult object, which cannot be directly concatenated with a pandas DataFrame. You need to convert the CursorResult to a pandas DataFrame first. Here's the corrected code:


from sqlalchemy import create_engine
import pandas as pd
Existing_Spec_Query = text("""
SELECT *
FROM [LSQD].[PartSpec]
WHERE PartId = :part_id AND PartRev= :Part_Rev
""")
# Assuming 'engine' is already defined and connected to your database with engine.connect() as connection: # Execute the query to fetch existing specifications Specresult = connection.execute(Existing_Spec_Query, {'part_id': part_id, 'Part_Rev': Part_Rev}) # Fetch all rows from the result set and convert to DataFrame existing_Spec = pd.DataFrame(Specresult.fetchall(), columns=Specresult.keys()) print(existing_Spec) # End of Getting Existing Part data # Concatenate the new specifications with the existing ones partspec_insert = pd.concat([partspec_insert, existing_Spec], ignore_index=True) # Update the 'PartRev' column to increment the revision number partspec_insert['PartRev'] = part_rev[0] + 1

Explanation:

  1. Fetch Results: The Specresult.fetchall() method fetches all rows from the result set.
  2. Convert to DataFrame: The pd.DataFrame(Specresult.fetchall(), columns=Specresult.keys()) converts the fetched results into a pandas DataFrame.
  3. Concatenate DataFrames: The pd.concat([partspec_insert, existing_Spec], ignore_index=True) concatenates the new specifications with the existing ones.

This should resolve the error and allow you to concatenate the dataframes successfully. If you have any further questions or need additional assistance, please let me know!

No comments:

Post a Comment