这是我在这里的第一篇文章,英语不是我的母语,我会尽量保持清晰。
我有一个来自以下形状的numpy数组(基本上是一个数据表):
[('information1', 'identifier1', length1)
('information2', 'identifier2', length2)
('information3', 'identifier3,identifier4', length3)
....
]
其中:
informationx
是string
,identifier
是string
,其中一个string
中包含一个或多个ID,length
是float
。我需要从该数组中提取包含有关一个标识符信息的所有行。
在SQL中,我会这样做
select * from array where id like "%identifier1%"
只有一个标识符时很容易:
extract = array[array[id_header] == identifier1]
是否有任何优雅而蟒蛇的方法(可能通过提取,选择或在何处)?
答案 0 :(得分:0)
您可以循环遍历每个索引,以查看标识符是否是您想要的:
lengths = []
for i in range(array.size[0]): #this should iterate through each row in the table
if array[i][1] == "identifierx":
lengths.append(array[i][2]) #adds the lenghts to a list containing all the lengths from the identifier you want
答案 1 :(得分:0)
在熊猫中这是一项简单的任务,考虑到您可以使用熊猫,使用
将数组转换为熊猫数据框
import pandas as pd
df = pd.dataFrame([your_array]) #creating data_frame
df.columns = ['col_1','col_2','col_3'] #setting column names
考虑到您已经为列设置了名称col_1,col_2,col_3。
用此代码子选择所需的列。
df_subset = df[ df['col_2'].str.contains('identifierx') ] #subselecting the data frame.
考虑到您不能使用熊猫,只能使用numpy。
new_lis = []
for idx in range(0,len(your_array)):
if( 'identifierx' in your_array[idx][1]):
new_lis.append(your_array[idx])
答案 2 :(得分:0)
那是一个很好的解决方案!只是想添加列表comp版本:
将它们放在(1000012,3)数组中,并填充上面的值以查询查询并获得以下计时:
import React, { Component } from 'react';
import App from './index';
class Data extends Component {
constructor(props) {
super(props);
this.state = {
names : [],
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
//Response
.then(response => response.json())
.then(output => {
let data = output;
//names in array
let listaimion = [];
for (let index = 0; index < data.length; index++) {
listaimion.push(data[index].name)
}
this.setState({names : listaimion})
})
}
render () {
return (
<div className = "Data">
<App names = {this.state.names} />
</div>
)
}
}
export default Data;
返回墙壁时间:875毫秒
对于列表组合:
%%time
new_lis = []
for idx in range(0,len(huge_data)):
if('identifier3' in huge_data[idx][1]):
new_lis.append(huge_data[idx])
返回墙壁时间:772毫秒
但是,是的-我尝试使用list comp + numpy索引进行求解,但是为了捕捉字符串,我使用了正则表达式,因此将其减慢到大约4.5s wah waaaah 。
好问题,好答案!