2017-09-22 28 views
1

我正在尋找最簡單直接的方式來返回數據框或具有值「1」的列名稱列表。返回某個值爲「1」的熊貓數據幀

說我開始與此:

import pandas as pd 

dates = pd.date_range('1/1/2017', periods=4, freq='D') 
df = pd.DataFrame({'W01': [0, 0, 0, 1], 'W02': [0, 1, 0, 0], 'W03': [0, 0, 0, 1] 
       }, 
      index = dates) 

df 

      W01 W02 W03 
2017-01-01 0 0 0 
2017-01-02 0 1 0 
2017-01-03 0 0 0 
2017-01-04 1 0 1 

而且我想,像這樣結束了一個數據幀。或者另一種更加智能的方式來將值分組爲「1」。

  Value X1 X2 
2017-01-01 1  NaN NaN  
2017-01-02 1  W02 NaN 
2017-01-03 1  NaN NaN 
2017-01-04 1  W01 W03 

另外,解決方案可能會返回一個像這樣的列表?

2017-01-01, NaN 
2017-01-02, W02 
2017-01-03, NaN 
2017-01-04, W01, W03 

我的實際數據框有85列和差不多700行。所以解決方案應該能夠匹配這些尺寸。

從大熊貓的get_value功能似乎不錯,但我無法弄清楚:df.get_value(dates, col="1")

我也可以使用拉姆達,但它並沒有提供所有我正在尋找的信息。 df.select(lambda x: x == '1', axis=1)

幫助?

+0

你試過['df.dot(df.columns + 「 」).str.strip(「」)'](https://stackoverflow.com/questions/46242976/elegant-方式對農產品-描述-的柱基柱頭數據/ 46243057#46243057)? – Psidom

回答

2

你可以

In [2784]: (df.apply(lambda x: ', '.join(x.index[x.astype(bool)]), axis=1) 
       .replace('', np.nan)) 
Out[2784]: 
2017-01-01   NaN 
2017-01-02   W02 
2017-01-03   NaN 
2017-01-04 W01, W03 
Freq: D, dtype: object 

或者,

In [2787]: df.apply(lambda x: pd.Series(x.index[x.astype(bool)]), axis=1) 
Out[2787]: 
       0 1 
2017-01-01 NaN NaN 
2017-01-02 W02 NaN 
2017-01-03 NaN NaN 
2017-01-04 W01 W03 
1

設立

df1=df.reset_index().melt('index') 
df1=df1[df1.value.eq(1)] 
df1.groupby('index')['variable'].apply(lambda x : ','.join(x)).to_frame().reindex(df.index) 

Out[846]: 
      variable 
2017-01-01  NaN 
2017-01-02  W02 
2017-01-03  NaN 
2017-01-04 W01,W03 
df1.groupby('index')['variable'].apply(lambda x : list(x)).apply(pd.Series).reindex(df.index) 
Out[852]: 
       0 1 
2017-01-01 NaN NaN 
2017-01-02 W02 NaN 
2017-01-03 NaN NaN 
2017-01-04 W01 W03