python - 从给定多索引的 pandas 数据帧中查找

标签 python pandas kaggle

在使用 pandas 处理 kaggle titanic 数据集时,我发现一个地方用 python 编写了显式循环,但我想知道是否有更有效的方法?考虑以下程序:

#!/usr/bin/python
import pandas as pd

# Assume that we have a dataframe with three fields
f = pd.DataFrame([ (0,1,1),
                   (1,0,0),
                   (1,1,1),
                   (1,1,0),
                   ],
                 columns=list('ABY'))

# and a multi index of A,B
idx = pd.MultiIndex.from_product([(0,1),(0,1)],
                                 names=list('AB'))

# For each idx I want a list of the values of F.Y for which A and B match. This
# can be done through the following loop:
e = []
for a,b in idx:
  e += [list(f.Y[(f.A==a) & (f.B==b)])]

s = pd.Series(e, index=idx, name='Y')
print s

# Yields:
# A  B
# 0  0        []
#    1       [1]
# 1  0       [0]
#    1    [1, 0]
# Name: Y, dtype: object

我的问题是是否可以在没有循环的情况下生成s

最佳答案

这是一种几乎相同的方法:

>>> f.groupby(["A", "B"])["Y"].apply(list).ix[idx]
A  B
0  0       NaN
   1       [1]
1  0       [0]
   1    [1, 0]
dtype: object

唯一的区别是,在没有匹配的情况下,这会给出 NaN 而不是空列表。不幸的是,您无法使用 fillna 将 NaN 替换为空列表,因为 this issue 。但是,您可以使用 dropna 删除它,并且在许多情况下,对于不匹配的情况,您实际上并不需要空项目。

关于python - 从给定多索引的 pandas 数据帧中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23316082/

相关文章:

python - matplotlibaxesgrid-附加颜色条?

python - 将整数列表转换为字符串

python - seaborn 散点图日期时间 x 轴太宽

python - Kaggle 泰坦尼克号与 tflearn 神经网络

python - "Numpy not Available"安装Pytorch XLA后

python - 使用 CSV 和 glob 重命名文件

python - 将 Flask 表单值转换为 int

python - 具有匹配标题的两个数据帧列之间的关联

Python 破折号 : Return subset of a data frame using drop-down menu

r - 尝试在 Kaggle 内核上运行 Rmd 文件时出错