Home > Net >  How can I print all data for each unique observation to its own PDF or CSV using R or Python?
How can I print all data for each unique observation to its own PDF or CSV using R or Python?

Time:05-20

Consider the following example dataframe. How can I group by Name and then write all information pertaining to each unique observation under the name column to a PDF, CSV, or Excel file? For example I would like all of Dave's information printed to a file named "Dave", all of Sal's information printed to a file named "Sal".

Name  | Score|  Date       | Test    | 
Dave  |  95  |  09/03/21   | Math    |
Dave  |  90  |  09/20/21   | History | 
Sal   |  85  |  09/18/21   | Math    |  
Jackie|  89  |  NA         | English | 
Sal   |  88  |  09/15/21   | Gym     |
Goat  |  18  |  09/17/21   | Gym     | 
Jackie|  82  |  10/16/21   | Art     |
Goat  |  3   |  10/17/21   | Math    |
Ty    |  25  |  09/28/21   | Math    |

Cheers

CodePudding user response:

In R:

names <- unique(df$Name)
for(nam in names){
  write.csv(x = df[df$Name== nam,], file = paste0(nam, ".csv"))
}

CodePudding user response:

You can just put everything in a loop:

for name in my_df['Name'].unique().tolist():
    new_df = my_df[my_df.Name ==name]
    file_path_name = 'your path'   name  '.csv'
    new_df.to_csv(file_path_name)

  • Related