1 回答
TA贡献1820条经验 获得超10个赞
为此,您可以使用to_csv创建 csv 字符串,然后调整列标题。您可以在 Excel 中打开 CSV 文件。
试试这个代码:
import pandas as pd
cols = ['Location','Machine Number','Net Funds','Net Revenue']
lst = [
['Location 1','123456',123, 76],
['Location 1','325462',869,522],
['Location 1','569183',896,234],
['Location 2','129756',535,542],
['Location 2','234515',986,516],
['Location 2','097019',236,512],
['Location 3','129865',976,251]]
df = pd.DataFrame(lst, columns=cols)
loclst = df['Location'].unique().tolist()
cc = ""
for loc in loclst:
dfl = df[df['Location']==loc][cols[1:]]
cc += ','.join(cols[1:]) + '\n' + loc+',,\n' + dfl.to_csv(index=False, header=False)
print(cc)
with open('out.csv','w') as f:
f.write(cc.replace('\r\n','\n'))
输出(out.csv)
Machine Number,Net Funds,Net Revenue
Location 1,,
123456,123,76
325462,869,522
569183,896,234
Machine Number,Net Funds,Net Revenue
Location 2,,
129756,535,542
234515,986,516
097019,236,512
Machine Number,Net Funds,Net Revenue
Location 3,,
129865,976,251
添加回答
举报