[英]Pandas Split column into multiple columns by multiple string delimiters
I have a dataframe:我有一个数据框:
id info
1 Name: John Age: 12 Sex: Male
2 Name: Sara Age: 22 Sex: Female
3 Name: Mac Donald Age: 32 Sex: Male
I'm looking to split the info column into 3 columns such that i get the final output as:我希望将信息列拆分为 3 列,以便获得最终输出:
id Name Age Sex
1 John 12 Male
2 Sara 22 Female
3 Mac Donald 32 Male
I tried using pandas split function.我尝试使用熊猫拆分功能。
df[['Name','Age','Sex']] = df.info.split(['Name'])
I might have to do this multiple times to get desired output.我可能需要多次执行此操作才能获得所需的输出。
Is there a better way to achieve this?有没有更好的方法来实现这一目标?
PS: The info column also contains NaN
values PS:信息列还包含NaN
值
Using Regex with named groups.对命名组使用正则表达式。
Ex:前任:
df = pd.DataFrame({"Col": ['Name: John Age: 12 Sex: Male', 'Name: Sara Age: 22 Sex: Female', 'Name: Mac Donald Age: 32 Sex: Male']})
df = df['Col'].str.extract(r"Name:\s*(?P<Name>[A-Za-z\s]+)\s*Age:\s*(?P<Age>\d+)\s*Sex:\s*(?P<Sex>Male|Female)") # Or if spacing is standard use df['Col'].str.extract(r"Name: (?P<Name>[A-Za-z\s]+) Age: (?P<Age>\d+) Sex: (?P<Sex>Male|Female)")
print(df)
Output:输出:
Name Age Sex
0 John 12 Male
1 Sara 22 Female
2 Mac Donald 32 Male
The regex is pretty tough to write / read, so you could replace with ,
for where you want separate into new columns and use str.split()
and pass expand=True
.正则表达式很难写/读,所以你可以替换为,
对于你想要分成新列的地方并使用str.split()
并传递expand=True
。 You will need to set the result back to three new columns that you create with df[['Name', 'Age', 'Sex']]
:您需要将结果设置回您使用df[['Name', 'Age', 'Sex']]
创建的三个新列:
df[['Name', 'Age', 'Sex']] = (df['info'].replace(['Name: ', ' Age: ', ' Sex: '], ['',',',','], regex=True)
.str.split(',', expand=True))
df
Out[1]:
id info Name Age Sex
0 1 Name: John Age: 12 Sex: Male John 12 Male
1 2 Name: Sara Age: 22 Sex: Female Sara 22 Female
2 3 Name: Mac Donald Age: 32 Sex: Male Mac Donald 32 Male
A quick oneliner can be一个快速的oneliner可以
df[['Name', 'Age', 'Sex']] = df['info'].str.split('\s?\w+:\s?', expand=True).iloc[:, 1:]
Split using someword:
and then add new columns.使用someword:
拆分,然后添加新列。
def process_row(row):
items = row.info.split(' ')
row['Name']=str(items[1]).strip()
row['Age']=str(items[3]).strip()
row['Sex']=str(items[5]).strip()
return row
df=pd.DataFrame({"info": ['Name: John Age: 12 Sex: Male', 'Name: Sara Age: 22 Sex:
Female', 'Name: Mac Donald Age: 32 Sex: Male']})
df['Name']=pd.NA #empty cell
df['Age']=pd.NA #empty cell
df['Sex']=pd.NA #empty cell
df[['info','Name','Age','Sex']]=df.apply(process_row, axis=1, result_type="expand")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.