When using agg() and join() methods on pandas DataFrame, sometimes you will get two below errors:
TypeError: sequence item 1: expected str instance, float found
, and:
FutureWarning: Dropping invalid columns in SeriesGroupBy.agg is deprecated. In a future version, a TypeError will be raised. Before calling .agg, select only columns which should be valid for the function.
df = df.groupby(['TowerId', 'City'], as_index=False).agg({'Site Type': '/'.join})
These errors may be due to the NaN value in your columns. Let’s try to create these errors with the below script:
import pandas as pd
import numpy as np
data = {
'TowerId': ['JAW-JT-KDL-0821', 'JAW-JT-KDL-0821', 'JAW-JT-KDL-0821', 'JAW-JT-KDL-0804', 'JAW-JT-KBM-0770', 'JAW-JT-KBM-0770'],
'City': ['Kuala Lumpur', 'Kuala Lumpur', 'Kuala Lumpur', 'Putra Jaya', 'Putra Jaya', 'Putra Jaya'],
'Site Type': ['Macro', 'Pico', np.nan, np.nan, 'Macro', np.nan]
}
df = pd.DataFrame(data)
df = df.groupby(['TowerId', 'City'], as_index=False).agg({'Site Type': '/'.join})
print(df)
You will find below errors:
1. Future Warning:

2. Type Error:

Let’s fill NaN with fillna() method before calling groupby() method, below the script:
import pandas as pd
import numpy as np
data = {
'TowerId': ['JAW-JT-KDL-0821', 'JAW-JT-KDL-0821', 'JAW-JT-KDL-0821', 'JAW-JT-KDL-0804', 'JAW-JT-KBM-0770', 'JAW-JT-KBM-0770'],
'City': ['Kuala Lumpur', 'Kuala Lumpur', 'Kuala Lumpur', 'Putra Jaya', 'Putra Jaya', 'Putra Jaya'],
'Site Type': ['Macro', 'Pico', np.nan, np.nan, 'Macro', np.nan]
}
df = pd.DataFrame(data)
print(df, end='\n\n')
# fillna before calling groupby
df = df.fillna('').groupby(['TowerId', 'City'], as_index=False).agg({'Site Type': '/'.join})
print(df)
Output:
