将 Pandas 中的两个数据合并在一起

Merging two data together in Pandas

我正在尝试将 pandas 中的数据连接在一起,但它似乎对我来说效果不佳。

我有一些数据想转换成数字,我能够做到这一点。然后我想让它重新加入数据集。

原始数据如下所示:

 CallDate            Agent          Group     Direction
0  2015-09-01         Adam          Billing    Inbound
1  2015-09-01         Nathaniel     Billing    Outbound
2  2015-09-01         Jessica       Claims     Inbound
3  2015-09-01         Tom           Billing    Outbound
4  2015-09-01         Jane          CCS        Inbound

这是我将组转换为数字的代码

data['Group']=data['Group'].astype(str)
data.Group=data['Group'].apply(lambda x:len(x))

这有效并给了我我正在寻找的东西 0 1 1 1 2 13 3 1 4 6

然后我尝试将其合并回组(基本上我想知道每个 name/number 对应什么)

y=pd.concat([data,data.Group], ignore_index=True)
y [:5]

但是结果和原来的数据库一样

是否有明显的我遗漏的东西或我没有想到的更简单的解决方法。

pd.concat()就是拼接两个DataFrame。我认为您正在尝试连接 a DataFrame.

中的两列
data
Out[42]: 
     CallDate      Agent    Group Direction
0  2015-09-01       Adam  Billing   Inbound
1  2015-09-01  Nathaniel  Billing  Outbound
2  2015-09-01    Jessica   Claims   Inbound
3  2015-09-01        Tom  Billing  Outbound
4  2015-09-01       Jane      CCS   Inbound

data.Group = data.Group + data.Group.apply(lambda x:" / "+str(len(x)))

data
Out[44]: 
     CallDate      Agent        Group Direction
0  2015-09-01       Adam  Billing / 7   Inbound
1  2015-09-01  Nathaniel  Billing / 7  Outbound
2  2015-09-01    Jessica   Claims / 6   Inbound
3  2015-09-01        Tom  Billing / 7  Outbound
4  2015-09-01       Jane      CCS / 3   Inbound

您可以在 pandas concat API documentation

中找到更多详细信息

更新新专栏,

data['Group_1'] = data.Group + data.Group.apply(lambda x:" / "+str(len(x)))

data
Out[56]: 
     CallDate      Agent    Group Direction      Group_1
0  2015-09-01       Adam  Billing   Inbound  Billing / 7
1  2015-09-01  Nathaniel  Billing  Outbound  Billing / 7
2  2015-09-01    Jessica   Claims   Inbound   Claims / 6
3  2015-09-01        Tom  Billing  Outbound  Billing / 7
4  2015-09-01       Jane      CCS   Inbound      CCS / 3

您可以使用 cat 函数连接 pandas 中的两个系列,检查 Documentation 此处的 cat 函数。

您还可以使用 len 函数轻松获取任何单词中的字符数 df.Group.str.len()

df['Group'] = df.Group.str.cat(df.Group.str.len().astype(str), sep=' => ')
df
Out[42]:
CallDate    Agent          Group         Direction
2015-09-01  Adam          Billing => 7   Inbound
2015-09-01  Nathaniel     Billing => 7   Outbound
2015-09-01  Jessica       Claims => 6    Inbound
2015-09-01  Tom           Billing => 7   Outbound
2015-09-01  Jane          CCS => 3       Inbound