返回一定值为“1”的数据帧

2024-09-24 10:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找返回值为“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行。所以解决方案应该能够匹配这些维度

pandas的get_value函数看起来不错,但我想不通:df.get_value(dates, col="1")

或者我可以使用lambda,但它并没有提供我要查找的所有信息。 df.select(lambda x: x == '1', axis=1)

救命啊


Tags: 数据方法lambdapandasdf列表getvalue
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

设置

df1=df.reset_index().melt('index')
df1=df1[df1.value.eq(1)]

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

相关问题 更多 >