转换为Pandas Dataframe的True / False值

时间:2017-07-02 16:12:29

标签: python pandas dataframe

我有一个相当大的数据框,看起来有点像这样:

  | obj1  | obj2  | obj3  |
  |------------------------
0 | attr1 | attr2 | attr1 |
1 | attr2 | attr3 | NaN   |
2 | attr3 | attrN | NaN   |

我是熊猫的新人(ish),但我无法找到让它看起来像这样的方法:

      | obj1  | obj2  | obj3 |
      ------------------------
attr1 | True | False | True  |
attr2 | True | False | False |
attr3 | True | False | False |

最狡猾/快速的方法是什么?

修改

我在数据框中没有包含所有属性的任何列。 我可以拥有一个具有其他任何地方都看不到的属性的Obj4

1 个答案:

答案 0 :(得分:6)

您需要set_index + eq

df = df.set_index('obj1', drop=False).rename_axis(None)
df = df.eq(df['obj1'], axis=0)
print (df)
       obj1   obj2   obj3
attr1  True  False   True
attr2  True  False  False
attr3  True  False  False

类似的解决方案:

df = df.set_index('obj1', drop=False).rename_axis(None)
df = df.eq(df.index.values, axis=0)
print (df)
       obj1   obj2   obj3
attr1  True  False   True
attr2  True  False  False
attr3  True  False  False

numpy解决方案:

df = pd.DataFrame(df.values == df['obj1'].values[:, None], 
                  index=df['obj1'].values, 
                  columns=df.columns)
print (df)
       obj1   obj2   obj3
attr1  True  False   True
attr2  True  False  False
attr3  True  False  False

编辑:

比较所有值并不容易:

vals = df.stack().unique()
L = [pd.Series(df[x].unique(), index=df[x].unique()).reindex(index=vals) for x in df.columns]
df1 = pd.concat(L, axis=1, keys=df.columns)
print (df1)
        obj1   obj2   obj3
attr1  attr1    NaN  attr1
attr2  attr2  attr2    NaN
attr3  attr3  attr3    NaN
attrN    NaN  attrN    NaN

df1 = df1.eq(df1.index.values, axis=0)
print (df1)
        obj1   obj2   obj3
attr1   True  False   True
attr2   True   True  False
attr3   True   True  False
attrN  False   True  False

EDIT1:

df1的另一种解决方案:

stacked = df.stack()
#reshape to MultiIndex
df1 = stacked.reset_index(name='A').set_index(['level_1','A'])
#MultiIndex with all possible values
mux = pd.MultiIndex.from_product([df1.index.levels[0], stacked.unique()])
#reindex by MultiIndex
df1 = df1.reindex(index=mux)
#replace non NaN values to second level of MultiIndex
df1['level_0'] = df1['level_0'].mask(df1['level_0'].notnull(),
                                     df1.index.get_level_values(1))
#reshape back
df1 = df1['level_0'].unstack(0)
print (df1)
        obj1   obj2   obj3
attr1  attr1    NaN  attr1
attr2  attr2  attr2    NaN
attr3  attr3  attr3    NaN
attrN    NaN  attrN    NaN