5 回答
TA贡献1862条经验 获得超6个赞
此解决方案也适用,使用unique:
data_list = [['mark', 1], ['tom', 2], ['mark', 3], ['mark', 4], ['tom', 5], ['stuart', 6]]
df = pd.DataFrame(data_list, columns=['name', 'id'])
for name in df['name'].unique():
df.loc[df['name'] == name].to_csv(name + '.csv')
TA贡献1830条经验 获得超3个赞
试试这个df.groupby
:
>>> master_df = pd.DataFrame(data_list, columns = ['name', 'ID'])
>>> for key, sub_df in master_df.groupby('name'):
sub_df.reset_index(drop=True).to_csv(key + '.csv')
对于您的功能:
def convertMerge(name_list):
df = pd.DataFrame(name_list,columns=['name','id'])
for key, sub_df in df.groupby('name'):
sub_df.reset_index(drop=True).to_csv(key + '.csv')
convertMerge(data_list)
如果打印它看起来像这样:
>>> master_df = pd.DataFrame(data_list, columns = ['name', 'ID'])
>>> for key, sub_df in master_df.groupby('name', sort=False):
print(key + '.csv')
sub_df.reset_index(drop=True)
# output:
mark.csv
name ID
0 mark 1
1 mark 3
2 mark 4
tom.csv
name ID
0 tom 2
1 tom 5
stuart.csv
name ID
0 stuart 6
TA贡献1735条经验 获得超5个赞
我认为这是您喜欢的解决方案......逻辑在convertMerge
data_list = [['mark', 1], ['tom', 2], ['mark', 3], ['mark', 4], ['tom', 5], ['stuart', 6]]
def convertMerge(name_list):
name = name_list[0]
df = pd.DataFrame([name_list],columns=['name','id'])
if not os.path.isfile(f'{name}.csv'):
df.to_csv(f'{name}.csv')
else:
df.to_csv(f'{name}.csv', mode='a', header=False)
for name_list in data_list:
convertMerge(name_list)
TA贡献1780条经验 获得超3个赞
你可以用apply做到这一点:
pd.DataFrame([['mark', 1], ['tom', 2], ['mark', 3], ['mark', 4], ['tom', 5], ['stuart', 6]], columns = ['name', 'ID']).groupby('name').apply(lambda d: d.to_csv(f'{d.name}.csv', index=False))
TA贡献1797条经验 获得超6个赞
这应该做你想做的:
data_list = [['mark', 1], ['tom', 2], ['mark', 3], ['mark', 4], ['tom', 5], ['stuart', 6]]
def convertMerge():
df = pd.DataFrame()
for name_list in data_list:
df = df.append(pd.DataFrame([name_list],columns=['name','id']))
[y.reset_index(drop = True).to_csv(x + '.csv', index = False) for x, y in df.groupby('name')]
convertMerge()
添加回答
举报