创建值为1的组合列表

时间:2018-03-13 14:20:02

标签: python list pandas

我有一个数据框,我想列出值为1的组合。我的数据类似于:

d = {'Australia' : pd.Series([0,1,1], index=['Australia', 'Belgium', 'France']),
     'Belgium' : pd.Series([1,0,1], index=['Australia','Belgium', 'France']),
    'France' : pd.Series([1,1,0], index=['Australia','Belgium', 'France'])}
df = pd.DataFrame(d)
df

我怎样才能创建一个类似于:

的列表
> [(Australia, Belgium), (Australia, Belgium), (Belgium, Australia),
> (Belgium, France), (France, Australia), (France, Belgium)]

1 个答案:

答案 0 :(得分:1)

我认为需要重新制作stack,按boolean indexing过滤并将MultiIndex导出到list of tuples

s = df.stack()

L = s[s == 1].index.tolist()
print (L)

[('Australia', 'Belgium'), ('Australia', 'France'), 
  ('Belgium', 'Australia'), ('Belgium', 'France'), 
  ('France', 'Australia'), ('France', 'Belgium')]

<强>详细

print (s)
Australia  Australia    0
           Belgium      1
           France       1
Belgium    Australia    1
           Belgium      0
           France       1
France     Australia    1
           Belgium      1
           France       0
dtype: int64