本文介绍了如何在 pandas 中的另一列中对一列中的字符串进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df=pd.DataFrame({'A':['abcde','fghij','klmno','pqrst'], 'B':[1,2,3,4]})
我想按列B对A列进行切片,例如:abcde[:1]=a, klmno[:3]=klm
但是两个陈述都失败了:
I want to slice column A by column B eg: abcde[:1]=a, klmno[:3]=klm
but two statements all failed:
df['new_column']=df.A.map(lambda x: x.str[:df.B])
df['new_column']=df.apply(lambda x: x.A[:x.B])
和
df['new_column']=df['A'].str[:df['B']]
new_column
返回NaN
尝试获取new_column
:
A B new_column
0 abcde 1 a
1 fghij 2 fg
2 klmno 3 klm
3 pqrst 4 pqrs
非常感谢您
推荐答案
您需要在axis=1 .apply.html"rel =" noreferrer> apply
方法来遍历行:
You need axis=1
in the apply
method to loop through rows:
df['new_column'] = df.apply(lambda r: r.A[:r.B], axis=1)
df
# A B new_column
#0 abcde 1 a
#1 fghij 2 fg
#2 klmno 3 klm
#3 pqrst 4 pqrs
一种惯用性较低但通常更快的解决方案是使用zip
:
df['new_column'] = [A[:B] for A, B in zip(df.A, df.B)]
df
# A B new_column
#0 abcde 1 a
#1 fghij 2 fg
#2 klmno 3 klm
#3 pqrst 4 pqrs
%timeit df.apply(lambda r: r.A[:r.B], axis=1)
# 1000 loops, best of 3: 440 µs per loop
%timeit [A[:B] for A, B in zip(df.A, df.B)]
# 10000 loops, best of 3: 27.6 µs per loop
这篇关于如何在 pandas 中的另一列中对一列中的字符串进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!