在pandas DataFrame中快速应用字符串操作 [英] Quickly applying string operations in a pandas DataFrame
本文介绍了在pandas DataFrame中快速应用字符串操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个DataFrame
,其中有10万行和一列name
.我想尽可能有效地将这个名字分成姓和名.我目前的方法是
Suppose I have a DataFrame
with 100k rows and a column name
. I would like to split this name into first and last name as efficiently as possibly. My current method is,
def splitName(name):
return pandas.Series(name.split()[0:2])
df[['first', 'last']] = df.apply(lambda x: splitName(x['name']), axis=1)
不幸的是,DataFrame.apply
确实非常慢.我有什么办法可以使此字符串操作几乎与numpy
操作一样快?
Unfortunately, DataFrame.apply
is really, really slow. Is there anything I can do to make this string operation nearly as fast as a numpy
operation?
谢谢!
推荐答案
尝试(要求熊猫> = 0.8.1):
Try (requires pandas >= 0.8.1):
splits = x['name'].split()
df['first'] = splits.str[0]
df['last'] = splits.str[1]
这篇关于在pandas DataFrame中快速应用字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文