Python 在pandas中,如何按公共值分组并基于该值拆分为列?
我有一个dataframe,它在“Status”列中具有相同的公共值。我需要将它拆分为两个不同的列及其旁边的URL 我试过了 DataFrame(df.groupby(['Labels','Pattern','Status])['Count'])没有按预期工作 我已经附上了df查询和清晰的理解图片 DFPython 在pandas中,如何按公共值分组并基于该值拆分为列?,python,pandas,Python,Pandas,我有一个dataframe,它在“Status”列中具有相同的公共值。我需要将它拆分为两个不同的列及其旁边的URL 我试过了 DataFrame(df.groupby(['Labels','Pattern','Status])['Count'])没有按预期工作 我已经附上了df查询和清晰的理解图片 DF import pandas as pd df = pd.DataFrame({'Labels': {0: 'Apple', 1: 'Apple', 2: 'Apple', 3: 'App
import pandas as pd
df = pd.DataFrame({'Labels': {0: 'Apple', 1: 'Apple', 2: 'Apple', 3: 'Apple', 4: 'Orange', 5: 'Orange', 6: 'Orange', 7: 'Orange', 8: 'Grapes', 9: 'Grapes'}, 'Pattern': {0: 'Red', 1: 'Red', 2: 'Green', 3: 'Green', 4: 'Good', 5: 'Good', 6: 'Bad', 7: 'Bad', 8: 'Violet', 9: 'Violet'}, 'Status': {0: 'Checked', 1: 'Not_Checked', 2: 'Checked', 3: 'Not_Checked', 4: 'Checked', 5: 'Not_Checked', 6: 'Checked', 7: 'Not_Checked', 8: 'Checked', 9: 'Not_Checked'}, 'Count': {0: 79, 1: 221, 2: 3, 3: 306, 4: 13, 5: 297, 6: 28, 7: 281, 8: 20, 9: 290}, 'Some_Link': {0: 'http://www.example.com/', 1: 'http://angle.example.com/', 2: 'https://example.com/', 3: 'http://www.example.com/www.php', 4: 'http://example.com/blow/bag', 5: 'https://www.example.com/?baby=brake', 6: 'https://www.example.org/?afternoon=approval&baseball=arithmetic', 7: 'https://example.net/babies/badge?amount=balance', 8: 'http://www.example.com/boundary/boat.aspx', 9: 'http://www.example.com/sssl.php'}, 'Some_Link2': {0: 'http://www.example.com/beef/approval', 1: 'https://www.example.com/qqa.php', 2: 'https://example.com/aswq.php', 3: 'http://www.example.com/believe/bike.php?amount=blade', 4: 'https://www.example.com/', 5: 'http://www.example.com/?beef=acoustics', 6: 'https://www.example.com/#apparatus', 7: 'https://www.example.com/asd.php', 8: 'http://basketball.example.com/bone/bedroom', 9: 'https://www.example.org/box/back'}})
实际输入
预期产出
与和一起使用,最后展平多索引:
df = df.set_index(['Labels','Pattern','Status']).unstack().sort_index(level=1, axis=1)
df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
df = df.reset_index()
与和一起使用,最后展平多索引:
df = df.set_index(['Labels','Pattern','Status']).unstack().sort_index(level=1, axis=1)
df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
df = df.reset_index()
签出数据透视表:签出数据透视表: