Pandas+Numpy:按数字数据类型过滤DF列会产生意外的行为

2024-07-04 15:57:42 发布

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

我有下表(示例,以方便任何想尝试的人):

serial;spectra;name;UKST;ra;dec;ra2000;dec2000;BJG;BJSEL;BJG_OLD;BJSELOLD;GALEXT;SB_BJ;SR_R;z;z_helio;obsrun;quality;abemma;Z_ABS;KBESTR;R_CRCOR;Z_EMI;NMBEST;SNR;ETA_TYPE 1;2;TGS436Z001;349;00:11:55.72;-32:32:55.2;00:14:27.05;-32:16:14.6;19.424;19.362;19.430;19.390;0.062;19.368;18.286;0.2981;0.2981;01SEP;4;1;0.2981;5;4.5700;0.2984;1;3.8;-99.90000 2;1;TGS496Z001;349;00:11:59.29;-33:14:41.3;00:14:30.55;-32:58:00.7;18.842;18.789;18.870;18.840;0.053;18.688;17.291;0.1229;0.1228;01OCT;5;1;0.1229;1;14.3800;-9.9990;0;47.6;-2.58920 3;1;TGS435Z001;349;00:11:49.37;-32:39:57.4;00:14:20.71;-32:23:16.8;18.320;18.265;18.350;18.310;0.055;18.336;17.138;0.1038;0.1038;01SEP;4;1;0.1038;1;9.3800;0.1032;1;28.4;-2.46500

sidenote:
You should have a pandas dataframe from the above '''data-sample''' as follows:
>>> import StringIO
>>> _tmp = StringIO.StringIO()
>>> _tmp.write('''data-sample''')
>>> _tmp.seek(0)
>>> import pandas
>>> df = pandas.read_csv(_tmp,delimiter=';')

我们得到的相应df包含以下dtypes信息:

^{pr2}$

我所要做的只是根据列的数据类型筛选列名;特别是,我希望保留数值列。所以,我想我应该做的就是检查他们的dtype是否是numpy.number

>>> filter(lambda c:df[c].dtypes == numpy.number,df.columns)
['BJG',
'BJSEL',
'BJG_OLD',
'BJSELOLD',
'GALEXT',
'SB_BJ',
'SR_R',
'z',
'z_helio',
'Z_ABS',
'R_CRCOR',
'Z_EMI',
'SNR',
'ETA_TYPE']

但正如我们所看到的,我得到的只是>float列,>int列被留在了。在

通过以下方式获得我想要的结果:

>>> filter(lambda c:df[c].dtypes == numpy.floating or df[c].dtypes == numpy.integer, df.columns)
['serial',
'spectra',
'UKST',
'BJG',
'BJSEL',
'BJG_OLD',
'BJSELOLD',
'GALEXT',
'SB_BJ',
'SR_R',
'z',
'z_helio',
'quality',
'abemma',
'Z_ABS',
'KBESTR',
'R_CRCOR',
'Z_EMI',
'NMBEST',
'SNR',
'ETA_TYPE']

(Obs:numpy.floatingnumpy.number在上述行给出相同的结果。)

这里的问题是:难道numpy.number不应该“表示”numpy中的任何数值类型(int、float、complex等)? 在阅读了numpy.core.numerictypes帮助页上相应的类层次结构之后,我对上述行为感到意外。。。 有人对此有何评论?我错过什么了吗?在

干杯。在


Tags: numpynumberdfabsoldtmpsbsr
1条回答
网友
1楼 · 发布于 2024-07-04 15:57:42

在列表对象中使用^{}并传递np.number

In [160]:
df.select_dtypes([np.number]).info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 0 to 2
Data columns (total 21 columns):
serial      3 non-null int64
spectra     3 non-null int64
UKST        3 non-null int64
BJG         3 non-null float64
BJSEL       3 non-null float64
BJG_OLD     3 non-null float64
BJSELOLD    3 non-null float64
GALEXT      3 non-null float64
SB_BJ       3 non-null float64
SR_R        3 non-null float64
z           3 non-null float64
z_helio     3 non-null float64
quality     3 non-null int64
abemma      3 non-null int64
Z_ABS       3 non-null float64
KBESTR      3 non-null int64
R_CRCOR     3 non-null float64
Z_EMI       3 non-null float64
NMBEST      3 non-null int64
SNR         3 non-null float64
ETA_TYPE    3 non-null float64
dtypes: float64(14), int64(7)
memory usage: 528.0 bytes

相关问题 更多 >

    热门问题