随机随机播放多个数据帧

时间:2020-03-10 12:30:12

标签: python pandas dataframe nlp

我有两个人之间的一连串对话(400)作为字符串(或更准确地说是纯文本文件),这的一个小例子可能是:

my_textfiles = ['john: hello \nmary: hi there \njohn: nice weather \nmary: yes',
            'nancy: hello \nbill: hi there \nnancy: nice weather \nbill: yes',
            'ringo: hello \npaul: hi there \nringo: nice weather \npaul: yes',
            'michael: hello \nbubbles: hi there \nmichael: nice weather \nbubbles: yes',
            'steve: hello \nsally: hi there \nsteve: nice weather \nsally: yes']

除了发言人姓名,我还注意到了每个发言人在对话中的角色(作为领导者还是跟随者,取决于他们是第一还是第二发言人)。然后,我有一个简单的脚本,可以通过将演讲者ID与内容分开来将每个对话转换为数据帧:

import pandas as pd
import re
import numpy as np
import random

def convo_tokenize(tf):
    turnTokenize = re.split(r'\n(?=.*:)', tf, flags=re.MULTILINE)
    turnTokenize = [turn.split(':', 1) for turn in turnTokenize]
    dataframe = pd.DataFrame(turnTokenize, columns = ['speaker','turn'])

    return dataframe

df_list = [convo_tokenize(tf) for tf in my_textfiles]

相应的数据框将构成更长的分析基础。但是,我现在希望能够对演讲者进行洗牌,以便我创建完全随机的(并且可能是废话)对话。例如,正在与拳头字符串中的Mary对话的John可能被随机分配为Paul(第三个字符串中的第二个发言人)。至关重要的是,我需要保持每个发言人的讲话顺序。同样重要的是,当随机分配新的发言人时,我保留了领导者/跟随者的混合体,这样我就不会与两个领导者或两个追随者进行对话了。

首先,我的想法是创建一个标准化的演讲者标签(其中1 =领导者,2 =关注者),并将每个DF分为一个子DF并存储在role_specific df列表中

def speaker_role(dataframe):
    leader = dataframe['speaker'].iat[0]
    dataframe['sp_role'] = np.where(dataframe['speaker'].eq(leader), 1, 2)

    return dataframe

df_list = [speaker_role(df) for df in df_list]

leader_df = []
follower_df = []

for df in df_list:
    is_leader = df['sp_role'] == 1
    is_follower = df['sp_role'] != 1

    leader_df.append(df[is_leader])
    follower_df.append(df[is_follower])

我已经得出结论,现在我可以简单地对子df之一(在这种情况下为follower_df)

follower_rand = random.sample(follower_df, len(follower_df)) 

到了这个阶段,我不确定下一步该怎么做。我怀疑我需要某种zip功能,但不确定到底是什么。我也不确定如何将转弯合并在一起,以便它们形成与最初相同的数据帧结构。假设Ringo(领导者)被随机分配给其中一个DF的Bubbles(跟随者),我希望有这样的东西...

 speaker   |   turn   |   sp_role
------------------------------------
  ringo       hello          1
 bubbles     hi there        2
  ringo    nice weather      1
 bubbles     yes it is       2

0 个答案:

没有答案