-
阿波罗的战车
此解决方案也适用,使用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')
-
牛魔王的故事
试试这个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 ID0 mark 11 mark 32 mark 4tom.csv name ID0 tom 21 tom 5stuart.csv name ID0 stuart 6
-
喵喔喔
我认为这是您喜欢的解决方案......逻辑在convertMergedata_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)
-
Helenr
你可以用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))
-
FFIVE
这应该做你想做的: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()