+1 vote
in Programming Languages by (56.8k points)

The highlighted line in the following code gives the error: "TypeError: cannot concatenate object of type '<class 'list'>'; only Series and DataFrame objs are valid"

factor_columns = [f'factor_{i}' for i in range(W.shape[1])]

feature_columns = [f'f_{i}' for i in range(H.shape[1])]

feature_df = pd.DataFrame(H, columns=feature_columns)

result_df = pd.concat([factor_columns, feature_df], axis=1)

result_df.to_csv(output_filename1, index=False)

How can this error be fixed? 

1 Answer

+1 vote
by (71.8k points)
selected by
 
Best answer

The concat() function of pandas needs either Series or DataFrame as arguments. You are providing a list, so your code is giving the error. To fix the error, convert the list to Series.

Make the following change in your code, which should solve the issue.

factor_columns = [f'factor_{i}' for i in range(W.shape[1])]

feature_columns = [f'f_{i}' for i in range(H.shape[1])]

feature_df = pd.DataFrame(H, columns=feature_columns)

result_df = pd.concat([pd.Series(factor_columns), feature_df], axis=1)

result_df.to_csv(output_filename1, index=False)


...