Skip to main content
 首页 » 编程设计

python之如何在 pandas 中使用 apply 函数返回多行

2024年09月07日32bonelee

上下文

我有一个包含成绩单的数据框。 df中的每一行都有一个唯一的ID、转录行和时间戳,每个ID在一天(或几天的跨度)内可以有多个对应关系。


示例代码如下!


我有什么:

#What I have starting out with. Df is ordered by CustomerID and Timestamp 
pd.DataFrame({'AgentID': 0, 'CustomerID': 1, 'Date': ['2018-01-21', '2018-01-21', '2018-01-22', '2018-01-22'], 'Timestamp': ['2018-01-21 16:28:54', '2018-01-21 16:48:54', '2018-01-22 12:18:54', '2018-01-22 12:22:54'], 'Transcript_Line':['How can I help you?', 'I need help with this pandas problem...', 'Did you get that problem resolved?', 'Nope I still suck at pandas']}) 


我需要什么:

#This is the final result 
 pd.DataFrame({'AgentID': 0, 'CustomerID': 1, 'Date': ['2018-01-21', '2018-01-22'], 'Transcript_Line': ['How can I help you?\nI need help with this pandas problem...', 'Did you get that problem resolved?\nNope I still suck at pandas']}) 

我需要组织和组合对应于同一天(按顺序)的所有成绩单(每行中的字符串)。


这是我到目前为止尝试过的 问题在这里:

def concatConvos(x): 
 
    if len(set(x.Date)) == 1: 
        return pd.Series({'Email' : x['CustomerID'].values[0],  
                        'Date': x['Date'].values[0], 
                    'Conversation' : '\n'.join(x['Transcript_Line'])}) 
    else:   
        rows = [] 
        for date in set(x.Date): 
            rows.append(pd.Series({'Email': x['CustomerID'].values[0], 
                                 'Date': date, 
                                 'Conversation': '\n'.join(x[x.Date == date].Transcript_Line)})) 
        return tuple(rows) 
 
data3 = data2.groupby('CustomerID').apply(concatConvos) 

对于客户只有一个通信日期的情况(这意味着他没有多次联系,第一种情况),我能够让它工作。

如果我尝试处理多于 1 的情况,那么我最终可能会遇到属性错误,因为该函数正在返回多个系列对象。

有没有更简单的方法来解决这个问题?

请您参考如下方法:

这不是最漂亮的解决方案,也不是最有效的解决方案,但我过去曾使用过类似的解决方案。我敢肯定可能有更有效的解决方案,而不是使用循环。我会给你原始代码,然后逐步分解它:

transcript_join = df.groupby(['CustomerID', 'Date']).apply(lambda f: f['Transcript_Line'].values.tolist()).to_dict() 
 
for x in transcript_join.keys(): 
    df.loc[(df['CustomerID']==x[0]) & (df['Date'] == x[1]), 'Combine'] = '\n'.join(transcript_join.get(x)) 
 
df.drop_duplicates(df.iloc[:,[0,1,2,5]]) 
 
# output below 
    AgentID CustomerID  Date    Timestamp   Transcript_Line Combine 
0   0   1   2018-01-21  2018-01-21 16:28:54 How can I help you? How can I help you?\nI need help with this pan... 
2   0   1   2018-01-22  2018-01-22 12:18:54 Did you get that problem resolved?  Did you get that problem resolved?\nNope I sti... 

首先,我使用变量 transcript_join 创建了一个包含所有响应的字典。关键是客户 ID,然后是日期。值是成绩单列表。

然后我遍历键并获取字典中客户 ID 和日期相同的位置,并使用 .join 将转录本组合到一个新列中。

最后,我删除了重复项,因为每个 Customer ID 和 Date 对都将包含相同的 Combine 列,因此现在会有重复项。我使用 iloc 去除输出中不需要的列,例如原始 Transcript 列以及 Timestamp