python - Filter pandas DataFrame columns -
i have dataframe this:
b c d 2000-01-03 -0.59885 0.18141 -0.68828 0.77572 2000-01-04 0.83935 0.15993 0.95911 -1.12959 2000-01-05 2.80215 -0.10858 -1.62114 -0.20170 2000-01-06 0.71670 -0.26707 1.36029 1.74254
i filter columns based on value of first row. e.g. want take columns first value >0. , result expect this:
b d 2000-01-03 0.18141 0.77572 2000-01-04 0.15993 -1.12959 2000-01-05 -0.10858 -0.20170 2000-01-06 -0.26707 1.74254
update jeff suggestion wrote code:
cols = [] firstrow = df.ix[0,:] in range(len(firstrow)): if firstrow[i]>0: cols.append(i) return df.ix[:, list(cols)].values.copy()
is there more elegant way this?
this using data generated below, can apply example. iloc[-2]
selects 2nd last row, , creates boolean array loc
takes boolean array , select applicable columns
in [2]: df = dataframe(np.random.randn(4,4),columns=list('abcd'), index=date_range('20000103',periods=4)) in [3]: df out[3]: b c d 2000-01-03 -0.132896 -0.151352 0.960943 -0.007701 2000-01-04 -1.653279 -1.101331 -2.083493 -1.920517 2000-01-05 -1.190868 0.983487 0.804209 0.962575 2000-01-06 0.232290 2.152097 0.414457 1.023253 in [6]: df.loc[:,df.iloc[-2]<0] out[6]: 2000-01-03 -0.132896 2000-01-04 -1.653279 2000-01-05 -1.190868 2000-01-06 0.232290
Comments
Post a Comment