Python 选择熊猫中的行并将其放入列表的更快方法?

Python 选择熊猫中的行并将其放入列表的更快方法?,python,pandas,Python,Pandas,我有一个600万行的数据帧,目前我正在执行以下操作: symbol = 'BPCL' rows=[] start = time.time() times = fut_df.timestamp.tolist() for t in times: s_df = fut_df[fut_df['timestamp'] == t] s_df.sort_values('expiry', inplace=True) if len(s_df) > 0: # s_df.

我有一个600万行的数据帧,目前我正在执行以下操作:

symbol = 'BPCL'
rows=[]
start = time.time()
times = fut_df.timestamp.tolist()
for t in times:
    s_df = fut_df[fut_df['timestamp'] == t]
    s_df.sort_values('expiry', inplace=True)
    if len(s_df) > 0:
        # s_df.reset_index(drop=True, inplace=True)
        # count += 1
        while len(s_df) < 3:
            s_df.loc[len(s_df)] = [0, 0, 0, 0, 0, 0, 0, 0, 0]
        rows.append([symbol, t,
                     s_df['close_under'].iloc[0], 
                     s_df['contractname'].iloc[0], s_df['close'].iloc[0],
                     s_df['contractname'].iloc[1], s_df['close'].iloc[1], 
                     s_df['contractname'].iloc[2], s_df['close'].iloc[2])
print(time.time() - start)
生成行后的预期输出我将把它们放入数据帧中:

symbol timestamp close_under m1 m1_close m2 m2_close m3 m3_close

BPCL 2020-04-30 15:29:52 371.85 BPCL20APRFUT 371.50  BPCL20MAYFUT 372.20 0 0


当前代码大约需要28小时才能通过数据帧。我怎样才能加快速度?我正在使用
多处理/concurrent.futures
一次浏览多个文件。

您可以尝试以下方法:

d = {'close_under':'first','close':'last','bid':'first'}
df = fut_df.groupby(['contractname', 'timestamp']).aggregate(d)
输出:


AttributeError:“DataFrame”对象没有“times”属性。如果您可以将问题浓缩为单个功能,例如“close”ing price,并提供一个功能较少但需要测试的数据点较多的示例,这将非常有帮助。作为一般性提示,你可以尽量避免所有的循环。@Andreas改变了它。它应该是
时间戳
谢谢,但似乎
符号
也没有定义。请注意,如果您尝试使用本机方法,pandas可以提供更高的性能。在你的情况下,我会尝试使用groupby。如果您能提供一个多个输入行但只有两个结果行的示例,那么我可以给您展示一个小示例。@Andreas yes避免循环是最好的,我仍在试图了解如何将操作矢量化。我正在添加更多数据点并减少功能。
d = {'close_under':'first','close':'last','bid':'first'}
df = fut_df.groupby(['contractname', 'timestamp']).aggregate(d)
                        close_under  close     bid
contractname timestamp                            
2020-04-30   15:29:52        371.85  371.5  371.85
             15:29:53        371.85  371.5  371.85
             15:29:54        371.00  371.5  372.00
             15:29:55        371.85  371.5  372.00
             15:29:56        371.90  372.7  372.15
             15:29:57        371.85  372.7  371.10
             15:29:58        371.90  371.5  371.40
             15:29:59        371.85  372.7  372.00