gpt4 book ai didi

python - 在 pandas.dataframe 中搜索优化选择

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:41 25 4
gpt4 key购买 nike

根据此选择,在包含 N 列(字符串、整数和 float )的 pandas.dataframe 中选择某些行的最有效方法是什么:

  • 遍历 2 列(整数)的所有组合。
  • 对于每个不同的组合,只保留一行(即所有列),最小值在第三列( float )

例如,对于 (titi,tutu) 与第三列是 tete 的组合:

  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)

注意:

  • 我确定这没有优化。
  • 我使用旧的“loc”方法,因为我不知道如何使用“query”

最佳答案

IIUC sort_values+drop_duplicates,如果你起诉 pandas 尽量不要使用 for 循环,大多数时候它比矢量化方法慢

df.sort_values('tete').drop_duplicates(['titi','tutu']).sort_index()
Out[583]:
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

关于python - 在 pandas.dataframe 中搜索优化选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49495181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com