在一个表中选择某些行最有效的方法是什么1.数据帧,包含N列(字符串、整数和浮点),根据此选择:
例如,对于第三列为tete的(titi,tutu)组合:
toto tata titi tutu tete
0 a 18 600 700 4.5
1 b 18 600 800 10.1
2 c 18 600 700 12.6
3 d 3 300 400 3.4
4 a 16 900 1000 6.0
5 a 18 600 800 10.1
6 c 3 300 400 3.0
7 a 16 900 1000 6.0
必须给出:
toto tata titi tutu tete
0 a 18 600 700 4.5
1 b 18 600 800 10.1
4 a 16 900 1000 6.0
6 c 3 300 400 3.0
目前,我从以下代码开始:
import pandas
indicesToKeep = []
indicesToRemove = []
reader = pandas.read_csv('/Users/steph/work/perso/sof/test.csv')
columns = reader.columns
for i in reader['titi'].unique():
#temp = reader[[:]].query('titi == i')#does not work !
temp = reader.loc[(reader.titi == i),columns]
for j in temp['tutu'].unique():
temp2 = temp.loc[(temp.tutu == j),columns]
minimum = min(temp2.tete)
indicesToKeep.append(min(
temp2[temp2.tete==minimum].index.tolist()))
################
# compute the complement of indicesToKeep
#but I don't remember the pythonic syntax
for i in range(len(reader)):
if i not in indicesToKeep:
indicesToRemove.append(i)
############################
reader = reader.drop(indicesToRemove)
注:
您可以按两列
titi
和tutu
分组,然后获得第三行tete
的最小值的行索引。完成后,只需查找行。你知道吗这将返回输出
这是如上所述的期望输出。你知道吗
groupby将确保保留这两列的所有可能组合。你知道吗
IIUC
sort_values
+drop_duplicates
,如果你起诉pandas试图不使用for循环,大多数时候它比矢量化方法慢相关问题 更多 >
编程相关推荐