使用来自不同数据帧的值在数据框中创建新行

时间:2017-11-18 04:45:45

标签: python pandas dataframe

我是Python或编码本身的新手。我需要你的帮助。所以我在这里有2个数据帧,包含用于数据学习过程的不同列。第一个数据帧包含带有PID的Intents和Responses。第二个数据框架保留了Intent和Phrases。我想在第一个数据帧中使用PID信息在包含团队的第二个数据帧中创建新列。

第一个数据帧(var'finalchat')

intent              response                                 Pid
PizzaDelivery       What Pizza do you like?                  1.4.6
WeatherForecast     What do you want to know the weather?    2
Emergency Number    Dial 911                                 10.8.9

第二个数据帧(var'ignatedatas')

intent              response                                 
PizzaDelivery       I want to order a pizza                  
WeatherForecast     What's the weather in Manila             
Emergency Number    What's the number to dial?                  

我想在第一个数据帧中获得Pid的第一个值。它们分别为1,2和3,并将其与硬编码条件进行比较,如果它们都为TRUE,那么它将在第二个数据帧中创建一个列为'Team'的列。

这是我正在尝试的代码,但是当我运行它时。它没有显示任何内容。

row_list = []
for index,row in intentdatas.iterrows():
    if ([re.search("1",index) is not None for index in 
    finalchat['Pid'].astype(str).str[0]] == 'TRUE'):
    row_list.append({'intent': row['intent'], 'phrases': row['phrases'], 
    'Team': 'Pizza'})
elif ([re.search("2",index) is not None for index in 
     finalchat['Pid'].astype(str).str[0]] == 'TRUE'):
     row_list.append({'intent': row['intent'], 'phrases': row['phrases'], 
     'Team': 'Weather'})
elif ([re.search("10",index) is not None for index in 
     finalchat['Pid'].astype(str).str[1]] == 'TRUE'):
    row_list.append({'intent': row['intent'], 'phrases': row['phrases'], 
    'Team': 'Emergency'})

intentdatas.head(10)

期待出局

Intent              Response                          Team                   
PizzaDelivery       I want to order a pizza           Pizza     
WeatherForecast     What's the weather in Manila      Weather      
Emergency Number    What's the number to dial?        Emergency

有人告诉我,我无法将列表与Singleton进行比较,这是TRUE语句。也许这就是为什么每当我打印intentdatas时都没有输出。请帮我。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以合并数据框,然后从Pid值映射团队。

team_map = {"1":"Pizza", "2":"Weather", "10":"Emergency"}

df = intentdatas.merge(finalchat[["intent","Pid"]], on="intent")

df.assign(team=df.Pid.apply(lambda x: team_map[x.split(".")[0]])).drop("Pid", 1)

             intent                      response          team
0     PizzaDelivery       I want to order a pizza         Pizza
1   WeatherForecast  What's the weather in Manila       Weather
2  Emergency Number    What's the number to dial?     Emergency