How to solve TypeError: sequence item 0: expected str instance, float found?

Viewed 5696

I am trying to use groupby method to combine the cell values (strings) of a column. But I faced the following error.

TypeError: sequence item 0: expected str instance, float found

The line which is giving error is

docs_per_topic = docs_df.groupby(['Topic'], as_index = False).agg({'Doc': ' '.join})

My original dataset has only one column ['Articles']. Below is the code where I read my CSV file.

data = pd.read_csv('my_file.csv')
data = data['Articles']

I cluster the articles and now I want to combine articles that are in the same cluster. For that, I am using the below code.

docs_df = pd.DataFrame(data, columns=["Doc"])
docs_df['Topic'] = cluster.labels_
docs_df['Doc_ID'] = range(len(docs_df))
docs_per_topic = docs_df.groupby(['Topic'], as_index = False).agg({'Doc': ' '.join})

I browsed for answers, I find this: How to fix this “TypeError: sequence item 0: expected str instance, float found” but I couldn't understand how to implement it in my case. I am fairly new to python. I would appreciate any suggestions or solutions to my problem.

1 Answers

It seems some missing values, so is possible remove rows with them before groupby:

docs_per_topic = docs_df.dropna(subset=['Doc']).groupby(['Topic'], as_index = False).agg({'Doc': ' '.join})

Or in groupby in lambda function:

docs_per_topic = docs_df.dropna(subset=['Doc']).groupby(['Topic'], as_index = False).agg({'Doc': lambda x: ' '.join(x.dropna())})

Another problem should be mixed values - strings with floats convert it to strings:

docs_per_topic = docs_df.assign(Doc = docs_df['Doc'].astype(str)).groupby(['Topic'], as_index = False).agg({'Doc': ' '.join})

docs_per_topic = docs_df.groupby(['Topic'], as_index = False).agg({'Doc': lambda x: ' '.join(x.astype(str))})
Related