Home > Enterprise >  Python - Copy a row from a csv and paste it in another csv
Python - Copy a row from a csv and paste it in another csv

Time:11-21

I'd like to understand how to copy a row from a .csv file and paste it in another .csv. Specifically, I have a large number of .csv files with the same column format. For each of these files, I should search for a string in a column and, if I find it, I have to append the corresponding row in another csv file.

E.g. --> the string is "Bob"

file1.csv

| First Name | Last Name | Age |
| Bob        | Arnald    | 22  |
| Alice      | Halton    | 25  |
| Tom        | Jackson   | 26  |

file2.csv

| First Name | Last Name | Age |
| Max        | Phoenix   | 33  |
| Bob        | Niall     | 23  |
| Sean       | Roger     | 26  |

The output file would be
out.csv \

| First Name | Last Name | Age |
| Bob        | Arnald    | 22  |
| Bob        | Niall     | 23  |

I tried using csv library, but it's not clear how to isolate a single row and append it into another csv file.

CodePudding user response:

Try this:

df1 = df1[df1['First Name'] == 'Bob']
df2 = df2[df2['First Name'] == 'Bob']
combined = pd.concat([df1, df2])

Note - pd.concat can be used on a list of any amount, therefore you can create a function to filter a df and iterate it over all your dfs, adding them to a list and then concatenating it.

  • Related