在这里我读了一个文件“userdata.xlsx”:
ID Debt Email Age User
1 7.5 john@email.com 16 John
2 15 john@email.com 15 John
3 22 john@email.com 15 John
4 30 david@email.com 22 David
5 33 david@email.com 22 David
6 51 fred@email.com 61 Fred
7 11 fred@email.com 25 Fred
8 24 eric@email.com 19 Eric
9 68 terry@email.com 55 Terry
10 335 terry@email.com 55 Terry
在这里,我按用户分组并为每个用户创建一个电子表格并将其输出为自己的 .xlsx 文件,如下所示:
ID Debt Email Age User
1 7.5 john@email.com 16 John
2 15 john@email.com 15 John
这是整个代码:
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import xlrd
df = pd.read_excel('userdata.xlsx')
grp = df.groupby('User')
for group in grp.groups:
grouptofile = (grp.get_group(group))
print(grouptofile)
print(group)
grouptofile.to_excel('%s.xlsx' % group , sheet_name='sheet1', index=False)
现在我只想保存选定的列来为每个用户保存。假设我只希望选择“ID”和“电子邮件”列。我学会了如何只选择某些列,如下所示:
selected = df[['ID','Email']]
我现在认为在这里添加 ID 和电子邮件是有意义的。
grp = df.groupby('User')
添加了“ID”和“电子邮件”
grp = df[['ID', 'Email']].groupby('User')
甚至可以组合 groupby 和 select 列吗?
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import xlrd
df = pd.read_excel('userdata.xlsx')
grp = df[['ID', 'Email']].groupby('User')
for group in grp.groups:
grouptofile = (grp.get_group(group))
print(grouptofile)
print(group)
grouptofile.to_excel('%s.xlsx' % group , sheet_name='sheet1', index=False)
不负相思意
MMMHUHU
相关分类