查找每列负值的索引

时间:2018-09-22 19:13:03

标签: python pandas

如何获得第一个负值出现的每一列的索引输出?

import pandas as pd

df1 = pd.DataFrame({'depth': [1.65, 2.15, 2.65, 3.15, 3.65, 4.15, 4.65, 5.15, 5.65, 6.15, 6.65, 7.15, 7.65, 8.15, 8.65],
               '400.0': [13.909261, 7.758734, 3.513627, 2.095409, 1.628918, 0.782643, 0.278548, 0.160153, -0.155895, -0.152373, -0.147820, -0.023997, 0.010729, 0.006050, 0.002356],
               '401.0': [14.581624, 8.173803, 3.757856, 2.223524, 1.695623, 0.818065, 0.300235, 0.173674, -0.145402, -0.144456, -0.142969, -0.022471, 0.010802, 0.006181, 0.002641],
               '402.0': [15.253988, 8.588872, 4.002085, 2.351638, 1.762327, 0.853486, 0.321922, 0.187195, -0.134910, -0.136539, -0.138118, -0.020945, 0.010875, 0.006313, 0.002927],
               '403.0': [15.633908, 8.833914, 4.146499, 2.431543, 1.798185, 0.874350, 0.333470, 0.192128, -0.130119, -0.134795, -0.136049, -0.019307, 0.012037, 0.006674, 0.003002],
               '404.0': [15.991816, 9.066159, 4.283401, 2.507818, 1.831721, 0.894119, 0.344256, 0.196415, -0.125758, -0.133516  , -0.134189, -0.017659, -0.013281,0.007053, 0.003061],
               '405.0': [16.349725, 9.298403, 4.420303, 2.584094, 1.865257, 0.913887, 0.355041, 0.200702, -0.121396, -0.132237, -0.132330, -0.016012, 0.014525, 0.007433, 0.003120]
               })

2 个答案:

答案 0 :(得分:2)

如何?

for column in df1:
    print(column, pd.DataFrame(df1[column])[df1 < 0].dropna().head(1).index)

打印出:

depth Int64Index([], dtype='int64')
400.0 Int64Index([8], dtype='int64')
401.0 Int64Index([8], dtype='int64')
402.0 Int64Index([8], dtype='int64')
403.0 Int64Index([8], dtype='int64')
404.0 Int64Index([8], dtype='int64')
405.0 Int64Index([8], dtype='int64')

答案 1 :(得分:1)

使用applynonzero

>>> df1.apply(lambda x:(x<0).nonzero()[0][:1].tolist())

400.0    [8]
401.0    [8]
402.0    [8]
403.0    [8]
404.0    [8]
405.0    [8]
depth     []
dtype: object