简体   繁体   中英

python pandas slice string based on other column

I am trying to slice a string in a column based on the values in two other columns (ideally method-chained):

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))

returns:

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

expected:

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

使用申请:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM