首页 > 解决方案 > Select Row by Username with Pandas

问题描述

I have a Table with multiple users and the data belonging to them. enter image description here

Now I want to create separate tables for each user like this:

enter image description here

Each account belonging to the users has a different ID so I can't use the ID to select.

How can I select the all Rows belonging to one specific name in the "User" row and then create separate table?

Also I would like take data out of a column and sort it into two new columns.

One example would be something like the email like: John.tomson@email.com and split it at the dot and create two new Columns "Name" and "Surname". enter image description here

标签: pythonexcelpython-3.xpandaspython-2.7

解决方案


分解方式 User

df.groupby('User').get_group('John')

   ID  User                  Email
0   1  John  john.tomson@email.com
1   2  John  john.tomson@email.com
2   3  John  john.tomson@email.com

也可以循环执行

grp = df.groupby('User')

for group in grp.groups:
    print(grp.get_group(group))

                   Email  ID   User
3  david.matty@email.com   4  David
4  david.matty@email.com   5  David
                   Email  ID  User
5  fred.brainy@email.com   6  Fred
                   Email  ID  User
0  john.tomson@email.com   1  John
1  john.tomson@email.com   2  John
2  john.tomson@email.com   3  John

拆分 Email

email_df = df['Email'].str.split(r'(.+)\.(.+)@', expand=True)]
pd.concat([df, email_df], axis=1)

                   Email  ID   User      0       1          2
0  john.tomson@email.com   1   John   john  tomson  email.com
1  john.tomson@email.com   2   John   john  tomson  email.com
2  john.tomson@email.com   3   John   john  tomson  email.com
3  david.matty@email.com   4  David  david   matty  email.com
4  david.matty@email.com   5  David  david   matty  email.com
5  fred.brainy@email.com   6   Fred   fred  brainy  email.com

推荐阅读