动态拆分数据框的列并将其存储为新列



我试图分割一列并存储最后一个"_"之后的部分。作为一个新的专栏。

import pandas as pd
import numpy as np
names= ['John', 'Jane', 'Brian','Suzan', 'John']
expertise = ['primary_chat', 'follow_email', 'repeat_chat', 'primary_video_chat', 'tech_chat']
data  = list(zip(names,expertise))
df = pd.DataFrame(data, columns=['Name', 'Communication'])
df


Name       Communication
0   John        primary_chat
1   Jane        follow_email
2  Brian         repeat_chat
3  Suzan  primary_video_chat
4   John           tech_chat

当我通过拆分列添加新列时:

df['Platform'] = df['Communication'].str.split('_', expand=True)[1]
df

Name       Communication Platform
0   John        primary_chat     chat
1   Jane        follow_email    email
2  Brian         repeat_chat     chat
3  Suzan  primary_video_chat    video
4   John           tech_chat     chat

但问题是,[1]占用了分割的第二部分。当我们只有一个"部分"时,这不是问题,第二部分才是我们需要的。但是当你有两个"视频"的时候,比如第三个"苏珊",[1]给你带来了短语"视频"。不是"email",我们应该在那里有[2]索引。

我们可以动态地获取"_"s的数量并使用这个值,但是,下面的代码即使它输出正确的值,当我在[]中使用它作为索引值时,我得到一个错误。

df['Communication'].str.count('_')
0    1
1    1
2    1
3    2
4    1
Name: Communication, dtype: int64

给了我正确的"_"数字。但是当我尝试在前一行代码中使用split()并创建新列时,我得到了一个错误

df['Platform'] = df['Communication'].str.split('_', expand=True)[df['Agent Expertise'].str.count('_')]

但是我得到错误…

也许我应该尝试使用apply()和lambda,但我想知道是否有一种方法来修复这个…

您可以使用正则表达式查找字符串末尾除_以外的所有字符(由$表示):

df['Platform'] = df['Communication'].str.extract('([^_]+)$')

您可以使用str.rsplit并将分割的数量限制为1:

df['Platform'] = df['Communication'].str.rsplit('_', n=1).str[1]
print(df)
# Output
Name       Communication Platform
0   John        primary_chat     chat
1   Jane        follow_email    email
2  Brian         repeat_chat     chat
3  Suzan  primary_video_chat     chat
4   John           tech_chat     chat

最新更新