Last updated: Apr 12, 2024
Reading time·3 min
The Pandas "TypeError: first argument must be an iterable of pandas objects,
you passed an object of type "DataFrame" occurs when you pass a single
DataFrame
to the pandas.concat()
method.
To solve the error, pass a list containing 2 DataFrames to the pandas.concat()
method.
Here is an example of how the error occurs.
import pandas as pd df1 = pd.DataFrame({ 'letter': ['A', 'B'], 'number': [1, 2] }) df2 = pd.DataFrame({ 'letter': ['C', 'D'], 'number': [3, 4] }) df3 = pd.concat(df1) # ⛔️ TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame" print(df3)
Notice that we passed a single DataFrame
to the
pandas.concat()
method.
pandas.concat()
methodTo solve the error, pass a list containing 2 DataFrames to the pandas.concat()
method.
import pandas as pd df1 = pd.DataFrame({ 'letter': ['A', 'B'], 'number': [1, 2] }) df2 = pd.DataFrame({ 'letter': ['C', 'D'], 'number': [3, 4] }) df3 = pd.concat([df1, df2]) # 0 A 1 # 1 B 2 # 0 C 3 # 1 D 4 print(df3)
The pandas.concat()
method takes a sequence of DataFrame objects.
Notice that we passed a list []
containing the two DataFrames to the method.
# ✅ Correct df3 = pd.concat([df1, df2])
Make sure you're not passing the DataFrames as multiple, individual arguments to the method.
# ⛔️ Incorrect df3 = pd.concat(df1, df2)
You can specify as many DataFrames as necessary in the list.
# ✅ Correct df4 = pd.concat([df1, df2, df3])
ignore_index
argument to True
In most cases, you will want to set the ignore_index
argument to True
.
import pandas as pd df1 = pd.DataFrame({ 'letter': ['A', 'B'], 'number': [1, 2] }) df2 = pd.DataFrame({ 'letter': ['C', 'D'], 'number': [3, 4] }) df3 = pd.concat([df1, df2], ignore_index=True) # letter number # 0 A 1 # 1 B 2 # 2 C 3 # 3 D 4 print(df3)
When the ignore_index
argument is set to True
, the index is reset in the
resulting DataFrame
.
Notice that the index
goes 0, 1, 2, 3 instead of 0, 1, 0, 1.
If you're trying to concatenate Series
objects, pass them in a list to
pandas.concat()
.
import pandas as pd s1 = pd.Series(['A', 'B']) s2 = pd.Series(['C', 'D']) s3 = pd.concat([s1, s2], ignore_index=True) # 0 A # 1 B # 2 C # 3 D # dtype: object print(s3)
You can also specify the axis
argument when calling pandas.concat()
.
When the axis
is set to 1
, the method will return a DataFrame
.
import pandas as pd s1 = pd.Series(['A', 'B']) s2 = pd.Series(['C', 'D']) df = pd.concat([s1, s2], ignore_index=True, axis=1) # 0 1 # 0 A C # 1 B D print(df)
The axis
argument determines the axis to concatenate along.
By default, the argument is set to 0
(index).
Setting the axis
argument to 1
means "concatenate along the columns axis".
You can learn more about the related topics by checking out the following tutorials: