python - 如何获取多个未定义列不为空的 pandas DataFrame 的第一个索引?

标签 python pandas numpy dataframe multiple-columns

我有一个包含多个列的数据框。我想获取第一行索引:

  • A列的值不为空
  • 至少存在 n 个值不为空的其他列

示例:如果我的数据框是:

          Date          A             B      C     D
0   2015-01-02          NaN           1      1    NaN
1   2015-01-02          NaN           2      2    NaN
2   2015-01-02          NaN           3      3    NaN
3   2015-01-02          1            NaN     4    NaN
5   2015-01-02          NaN           2      NaN  NaN
6   2015-01-03          1            NaN     6    NaN
7   2015-01-03          1             1      6    NaN
8   2015-01-03          1             1      6     8

如果 n=1 我会得到 3

如果 n=2 我会得到 7

如果 n=3 我会得到 8

最佳答案

这是一次性获取不同 n 的 索引的一种方法 -

def numpy_approach(df, reference='A'):
    df0 = df.iloc[:,df.columns != 'Date']
    valid_mask = df0.columns != reference
    mask = ~np.isnan(df0.values)
    count = mask[:,valid_mask].sum(1) * mask[:,(~valid_mask).argmax()]
    idx0 = np.searchsorted(np.maximum.accumulate(count),[1,2,3])
    return df.index[idx0]

样本运行-

In [555]: df
Out[555]: 
         Date    A    B    C    D
0  2015-01-02  NaN  1.0  1.0  NaN
1  2015-01-02  NaN  2.0  2.0  NaN
2  2015-01-02  NaN  3.0  3.0  NaN
3  2015-01-02  1.0  NaN  4.0  NaN
5  2015-01-02  NaN  2.0  NaN  NaN
6  2015-01-03  1.0  NaN  6.0  NaN
7  2015-01-03  1.0  1.0  6.0  NaN
8  2015-01-03  1.0  1.0  6.0  8.0

In [556]: numpy_approach(df, reference='A')
Out[556]: Int64Index([3, 7, 8], dtype='int64')

In [557]: numpy_approach(df, reference='B')
Out[557]: Int64Index([0, 7, 8], dtype='int64')

In [558]: numpy_approach(df, reference='C')
Out[558]: Int64Index([0, 7, 8], dtype='int64')

In [568]: numpy_approach(df, reference='D')
Out[568]: Int64Index([8, 8, 8], dtype='int64')

关于python - 如何获取多个未定义列不为空的 pandas DataFrame 的第一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43520275/

相关文章:

Python 从地址生成纬度/经度点

python - Python 中的快速逆矩阵和转置矩阵

python - 如何使用 NumPy 数组实现字典?

python - 谷歌 API Python unauthorized_client : Unauthorized client or scope in request

python - 类型错误 : 'str' object is not callable with win32com interfacing with Attachmate

Python矩阵(列表列表)到字典

python - Pandas 创建一个新列来说明文件是否存在

python - Groupby,在数据帧中基于索引值(每小时时间戳) - 当索引中断时

python - 将二维数组(字段)添加到 numpy recarray

python - 如何解析日期进行比较 时间范围比较特定值