魔力Python—— 查找列表项与np.genefromtxt()

Part1

Background

python,想获取列表中满足某一要求的所有列表项的索引。如这样的列表:a = [‘id:123’,’is_a:ja’,’name:ad’,’is_a: dj’],需得到含有‘is_a’的两个列表项索引。

Solution

startswith()

1
2
3
a = ['id:123','is_a:ja','name:ad','is_a: dj']
[ i for i, word in enumerate(a) if word.startswith('is_a:') ]
>>>[1,3]
1
2
3
a = ['id:123','is_a:ja','name:ad','is_a: dj']
[ i for i, word in enumerate(a) if re.search('is_a:',word) ]
>>>[1,3]

Part2

Background

在读取数据文本时,遇到这样的问题,结构文本数据值默认为空,或者是缺失的,这时加载时,就需要对其进行处理,设定一个默认值。

Solution

numpy.genefromtxt()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'''
将test.csv里的空值用'0'来代替,test.txt内容如下:
1,,1,
,,1,
,,,
,1,,
'''
import numpy as np
data = np.genfromtxt('test.csv', delimiter=',', missing_values=[''],filling_values='0')
>>>data
[[ 1. 0. 1. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 0.]
[ 0. 1. 0. 0.]]
Keep calm and carry on
分享