Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas: concatenating empty df with existing df

I have two df:

  • historical df: which is empty with only 5 columns: ["count_date", "device", "hour", "count", "average_speed"]
  • result df: which has 38688 rows and 5 columns (sames ones as historical df)

When I’m trying to concatenate them:

historical_df = pd.concat(["historical_df", "result"], axis=0, ignore_index=True)

I get the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

I’ve checked and both df are DataFrame types.

Any idea where it could come from? Is there something I’m missing?

Thank you in advance for your help.

>Solution :

Your code is correct apart from one minute detail:
According to the official documentation of pandas.concat we have:

objs: a sequence or mapping of Series or DataFrame objects

In other words, the first parameter ought to be a list of pandas DataFrames; not a list of strings. In your code this would mean:

historical_df = pd.concat([historical_df, result], axis=0, ignore_index=True)

Note that I simply removed the quotes for the strings.

Here is a dummy code that will produce the desired result:

import pandas as pd

# create an empty dataframe with column names
result = pd.DataFrame(columns=['count_date', 'device', 'hour', 'count', 'average_speed'])

# create an existing dataframe
historical_df = pd.DataFrame({'count_date': ['2023-05-09', '2023-05-10'], 
                            'device': ['A', 'B'], 
                            'hour': [8, 9],
                            'count': [100, 200],
                            'average_speed': [50.0, 60.0]})

# concatenate result with historical_df
historical_df = pd.concat([result, historical_df])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading