我有一个 MySQL 查询正在执行 groupby 并以以下形式返回数据:
ID | Boolean | Count
有时表中没有某个 bool 状态的数据,因此单个 ID 的数据可能会像这样返回:
1234 | 0 | 10
但是我需要这种形式的下游分析:
1234 | 0 | 10
1234 | 1 | 0
索引为 [ID, Boolean]。
从 Google 和 SO 的查询来看,让 MySQL 进行这种转换似乎有点痛苦。有没有一种简单的方法可以在 Pandas 中做到这一点?我在文档或 Pandas 食谱中找不到任何有用的内容。
您可以假设我已经将数据加载到没有索引的 Pandas 数据框中。
谢谢。
最佳答案
我会将数据帧的索引设置为 ID
和 Boolean
列,并根据唯一值的笛卡尔积构造一个新索引。
看起来像这样:
import pandas
indexcols = ['ID', 'Boolean']
data = pandas.read_sql_query(engine, querytext)
full_index = pandas.MultiIndex.from_product(
[data['ID'].unique(), [0, 1]],
names=indexcols
)
data = (
data.set_index(indexcols)
.reindex(full_index)
.fillna(0)
.reset_index()
)
关于python - 填充 Pandas 中缺失的 bool 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626112/