'Export DF to seperate .csv files based on column name
I want to split a dataframe based on the column name and export it in seperate .csv files. How can i do this?
import pandas as pd
from google.colab import files
uploaded = files.upload()
import io
df1 = pd.read_csv(io.BytesIO(uploaded['Your Keywords Clustered.csv']))
df_list = [d for _, d in df1.groupby(['Cluster_Name'])]
print(df_list)
Example .csv file:
a,1
a,2
a,3
b,4
b,5
b,5
Solution 1:[1]
If new filenames are henerated from names of groups use for loop with DataFrame.to_csv:
for name, d in df1.groupby(['Cluster_Name']):
d.to_csv(f'{name}.csv', index=False)
If need remove Cluster_Name column in each file (because same value):
for name, d in df1.groupby(['Cluster_Name']):
d.drop(['Cluster_Name'], axis=1).to_csv(f'{name}.csv', index=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jezrael |
