Pandas 系统地识别缺失的多指标分类值
Pandas systematically identify missing multi-index categorical values
我有以下数据框,在 ID 列中我们可以有 2 个反馈,好的或坏的。我不知道如何系统地识别用户是否缺少反馈,如果缺少反馈,请在级别 1 中添加一个包含缺少反馈的新行,并将所有值加 0。
import pandas as pd
df = {'ID': ['Good','Good','Good', 'Bad', 'Bad', 'Bad', 'Good', 'Good', 'Bad'],
'USERS' : ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'C'],
'DATE_VIEW': ['16/05/2019','16/05/2019', '16/05/2019', '18/03/2020', '18/03/2020', '18/03/2020', '18/03/2020', '18/03/2020', '18/03/2020'],
'VALUES': [1, 3, 4, 5, 6, 7, 8, 1, 2]
}
df = pd.DataFrame(df)
df = pd.pivot_table(df, index=['USERS', 'ID'], columns='DATE_VIEW', values='VALUES', aggfunc='sum', fill_value=0)
这是预期的输出:
尝试:
idx = pd.MultiIndex.from_product(
[
df.index.get_level_values(0).unique(),
df.index.get_level_values(1).unique(),
],
names=["USERS", "ID"],
)
df = df.reindex(idx, fill_value=0)
print(df)
打印:
DATE_VIEW 16/05/2019 18/03/2020
USERS ID
A Bad 0 6
Good 5 8
B Bad 0 12
Good 3 1
C Bad 0 2
Good 0 0
unstack
和 stack
df.unstack(fill_value=0).stack()
DATE_VIEW 16/05/2019 18/03/2020
USERS ID
A Bad 0 6
Good 5 8
B Bad 0 12
Good 3 1
C Bad 0 2
Good 0 0
我有以下数据框,在 ID 列中我们可以有 2 个反馈,好的或坏的。我不知道如何系统地识别用户是否缺少反馈,如果缺少反馈,请在级别 1 中添加一个包含缺少反馈的新行,并将所有值加 0。
import pandas as pd
df = {'ID': ['Good','Good','Good', 'Bad', 'Bad', 'Bad', 'Good', 'Good', 'Bad'],
'USERS' : ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'C'],
'DATE_VIEW': ['16/05/2019','16/05/2019', '16/05/2019', '18/03/2020', '18/03/2020', '18/03/2020', '18/03/2020', '18/03/2020', '18/03/2020'],
'VALUES': [1, 3, 4, 5, 6, 7, 8, 1, 2]
}
df = pd.DataFrame(df)
df = pd.pivot_table(df, index=['USERS', 'ID'], columns='DATE_VIEW', values='VALUES', aggfunc='sum', fill_value=0)
这是预期的输出:
尝试:
idx = pd.MultiIndex.from_product(
[
df.index.get_level_values(0).unique(),
df.index.get_level_values(1).unique(),
],
names=["USERS", "ID"],
)
df = df.reindex(idx, fill_value=0)
print(df)
打印:
DATE_VIEW 16/05/2019 18/03/2020
USERS ID
A Bad 0 6
Good 5 8
B Bad 0 12
Good 3 1
C Bad 0 2
Good 0 0
unstack
和 stack
df.unstack(fill_value=0).stack()
DATE_VIEW 16/05/2019 18/03/2020
USERS ID
A Bad 0 6
Good 5 8
B Bad 0 12
Good 3 1
C Bad 0 2
Good 0 0