首页 > 解决方案 > 基于其他列的python pandas切片字符串

问题描述

我正在尝试根据其他两列中的值(理想情况下是方法链接的)对列中的字符串进行切片:

df = pd.DataFrame({'a':["abcde", "abcdefg"], 'start':[0,3], 'end':[3,5]})
df.assign(c = lambda x: x.a.str.slice(x.start,x.end))

返回:

         a  start  end    c
0    abcde      0    3  NaN
1  abcdefg      3    5  NaN

预期的:

         a  start  end    c
0    abcde      0    3  abc
1  abcdefg      3    5  def

标签: pythonpandas

解决方案


使用适用:

df.assign(c = lambda x: x.apply( lambda s: s['a'][s.start:s.end],axis=1))

推荐阅读