0

I need to concatenate multiple matrices (containing numbers and strings) in a loop, so far I wrote this solution but I don't like to use a dummy variable (h) and I'm sure the code could be improved.

Here it is:

h = 0
for name in list_of_matrices:
        h +=1        
        Matrix = pd.read_csv(name)
        if h == 1:
            Matrix_final  = Matrix 
            continue
        Matrix_final  = pd.concat([Matrix_final,Matrix]) 

For some reason if I use the following code I end up having 2 matrices one after the other and not a joint one (so this code is not fitting):

li = []
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)
Felix
  • 1
  • 1
  • 3
    Does this answer your question? [Import multiple csv files into pandas and concatenate into one DataFrame](https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe) – Shaido Jun 13 '22 at 07:28
  • Sadly no, I already tried that code but it fails to concatenate the kind of matrices I have. I end up having 2 matrices one after the other but completely disconnected, while I want them to be one single dataframe. Eg. Matrix1: A B C 1 0 a 2 0 b 3 1 b Matrix2: A B C 4 80 f 5 80 f 6 81 e I want: A B C 1 0 a 2 0 b 3 1 b 4 80 f 5 80 f 6 81 e – Felix Jun 13 '22 at 07:42
  • The new code you added is missing a key step, the above will only give you a list of dataframes. You need to add `pd.concat(li, ignore_index=True)` afterwards. – Shaido Jun 13 '22 at 08:03
  • @Shaido if I try it returns "TypeError: cannot concatenate object of type ''; only Series and DataFrame objs are valid" – Felix Jun 14 '22 at 13:25
  • @Shaido if I try with 3 pandas it returns a structure of the type [ [A [B [C] ] ] instead of [ABC] – Felix Jun 14 '22 at 13:31
  • 1
    Update: Solved by creating a new object NEW = pd.concat(li, ignore_index=True). Apparently redefining li as li = pd.concat(li, ignore_index=True) is not an option. Thank you! – Felix Jun 14 '22 at 13:43

0 Answers0