我有一个名为 data.csv 的数据文件
name,value
A,10
1,20
B,30
3,20
...
所以问题是我使用 numpy 和 mlab 来加载这个 csvfile
data = mlab.csv2rec(data.csv)
我有一个问题,我怎样才能过滤掉data.name is a number
?
例如:输出应该是
1,20
3,20
If you want to filter the recarray while preserving the structure of the filtered records:
filter_idx = [i for i, s in enumerate(data.names) if s.isdigit()]
data[filter_idx]
gives
rec.array([('1', 20), ('3', 20)],
dtype=[('names', 'S1'), ('value', '<i4')])
If you just want to print out the filtered records like in your example output I would just do it and catch the exceptions:
for rec in data:
try:
print int(rec.names), rec.value
except:
pass
prints
1 20
3 20
您可以使用isinstance()。
for i in data:
if isinstance(data.name, int):
print data.name, data.value
或者
new_data = list(x for x in data if isinstance(x.name, int))
在这个例子中工作正常:
data = [[1,10], ["a", 20], [2, 30], ["b", 40], [3, 50]]
new_data = list(x for x in data if isinstance(x[0], int))
print new_data