使用.apply函数时如何附加到数据框

时间:2018-10-01 12:06:54

标签: python python-3.x pandas

每当持续时间少于11秒时,我尝试将数据帧M附加到空数据帧Linked_df上。 以下代码附加了一个数据框:

Linked_df=pd.DataFrame()
Linked=pd.DataFrame()
#for each unique date
for unq_date in Unique_Dates:
    #obtain dataframe of Mi and Ri of a specific date
    #add a column for index to track orignal index
    M=Mi.loc[(pd.to_datetime(Mi['EventDate']) == unq_date) ]
    R=Ri.loc[(pd.to_datetime(Ri['EventDate']) == unq_date) ]
    #Check if unique date exist in M
    Linked_df = R.apply(lambda row: create_dur(row['start_DateTime'], M,Linked_df), axis=1)
    Linked=Linked.append(Linked_df,ignore_index=True)

该函数调用并将M附加到数据帧Linked_df中:

def create_dur(row,M,Linked_df):
    M['duration']=(M['Event Read Time'] - row).dt.total_seconds()
    M.loc[M.duration < 0, 'duration'] = (row-M['Event Read Time']).dt.total_seconds()
    M=M.loc[M.duration < 11]
    #print(M['duration'])
    #print(M)
    row1 = pd.DataFrame(M)
    #Linked_df=pd.concat([Linked_df, row1], ignore_index=True)
    Linked_df=Linked_df.append(M,ignore_index=True)
    print(Linked_df)
    return Linked_df

函数的输出:

    EventDate             Id_str EventTime     Event Read Time       lat  \
0  2017-11-09  72057594042646832  01:13:24 2017-11-09 01:13:24 -27.73409   
1  2017-11-09  72057594042646832  01:13:29 2017-11-09 01:13:29 -27.73200   
2  2017-11-09  72057594042646848  01:13:30 2017-11-09 01:13:30 -27.73192   
3  2017-11-09  72057594042646864  01:13:32 2017-11-09 01:13:32 -27.73399   
4  2017-11-09  72057594042646880  01:13:33 2017-11-09 01:13:33 -27.73398   

       long  Speed  Sprung Weight  Frame Torque  ind_val_Mi  duration  
0  22.96531    9.0          468.0          88.0            101995       6.0  
1  22.97351   36.0          280.0          -4.0            101996       1.0  
2  22.97347   36.0          270.0         -10.0            101997       0.0  
3  22.96537    0.0          480.0          85.0            101998       2.0  
4  22.96537    2.0          489.0          89.0            101999       3.0  
    EventDate             Id_str EventTime     Event Read Time       lat  \
0  2017-11-09  72057594042646832  01:13:29 2017-11-09 01:13:29 -27.73200   
1  2017-11-09  72057594042646848  01:13:30 2017-11-09 01:13:30 -27.73192   
2  2017-11-09  72057594042646864  01:13:32 2017-11-09 01:13:32 -27.73399   
3  2017-11-09  72057594042646880  01:13:33 2017-11-09 01:13:33 -27.73398 

结果未添加到空白数据框中。似乎正在更新数据框。是什么原因?我尝试了concat但得到一个空列表。

0 个答案:

没有答案