Suppose the following csv is local.
sample.csv
id,age,name,money
111,11,sato,1100
222,22,suzuki,20000
333,33,takahashi,330000
444,44,tanaka,440000
555,55,ito,500000
666,66,yamamoto,800000
777,77,nakamura,1000000
Based on this, create a new csv that satisfies the following.
gencsv.py
import pandas as pd
id_list = []
age_list = []
name_list = []
money_list = []
read_csvfile = 'sample.csv'
def stack_data():
global name_list
global id_list
global age_list
global money_list
#Read data from csv
data = pd.read_csv(read_csvfile)
#Store in each list
for name in data['name']:
name_list += [name]
for i in data['id']:
id_list += [i]
for age in data['age']:
age_list += [age]
for money in data['money']:
money_list += [money]
def generate_csv():
#Substitute the acquired data in the data frame
for i in range(len(name_list)):
df = pd.DataFrame({
'name': name_list[i],
'age': age_list[i],
'money': money_list[i],
},index=[i,])
csv_title = 'personID=' + str(id_list[i]) + '.csv'
#Generate csv based on data frame
df.to_csv(csv_title, index=False)
print(csv_title+'Was generated')
print("All created")
stack_data()
generate_csv()
$ python3 gencsv.py
personID=111.csv was generated
personID=222.csv was generated
personID=333.csv was generated
personID=444.csv was generated
personID=555.csv was generated
personID=666.csv was generated
personID=777.csv was generated
All created
Recommended Posts