1

pandas で kaggle titanic データセットを操作しているときに、Python で明示的なループを記述した場所を 1 つ見つけましたが、もっと効率的な方法があるかどうか疑問に思っています。次のプログラムを検討してください。

#!/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、ループなしで生成できるかどうかです。

4

1 に答える 1