在使用 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
没有循环的情况下生成?