【发布时间】:2016-10-24 15:35:01
【问题描述】:
例如,我有以下数据作为列表:
l = [['A', 'aa', '1', '300'],
['A', 'ab', '2', '30'],
['A', 'ac', '3', '60'],
['B', 'ba', '5', '50'],
['B', 'bb', '4', '10'],
['C', 'ca', '6', '50']]
现在对于'A'、'B' 和'C',我想获取它们的最后一次出现,即:
[['A', 'ab', '3', '30'],
['B', 'bb', '4', '10'],
['C', 'ca', '6', '50']]
或更进一步,这些事件中的第三列,即:
['3', '4', '6']
目前,我的处理方式是:
import pandas as pd
df = pd.DataFrame(l, columns=['u', 'w', 'y', 'z'])
df.set_index('u', inplace=True)
ll = []
for letter in df.index.unique():
ll.append((df.ix[letter, 'y'][-1]))
然后我%timeit,它显示:
>> The slowest run took 27.86 times longer than the fastest.
>> This could mean that an intermediate result is being cached.
>> 1000000 loops, best of 3: 887 ns per loop
只是想知道是否有一种方法可以使用比我的代码更少的时间来做到这一点?谢谢!
【问题讨论】:
-
你目前的低效方式是什么?
-
为什么
A的最后一次出现是第二个而不是第三个数组? -
在您的列表中使用反向然后 - 可能与 What is the best way to get the first item from an iterable matching a condition? 重复
-
@jonrsharpe 我首先将此列表转换为熊猫数据框,将第一列设置为索引,然后迭代唯一索引值以提取每个索引的最后一次出现,我认为这不是有效的所以我正在寻找更好的方法来做到这一点。
-
"Better" 很难判断没有: 1. 我们试图变得更好;和 2. 你如何更好地衡量。
标签: python list data-manipulation