3 回答

TA貢獻1880條經驗 獲得超4個贊
用于圍繞 delimiterSeries.str.split拆分列,然后使用列表理解壓縮拆分列并處理值:string|zipoccurence
df['string'] = ['|'.join(s[i:]) for i, s in zip(df['occurrence'], df['string'].str.split('|'))]
結果:
print(df)
occurrence string
0 7 8|9|10|11|12
1 2 12.2|13.6|14.7
2 0 1|2|3
3 3 4|5|6|7|8
4 4 5|6.2|7|8.1
5 0 1|2|3|4|5
性能(使用 測量timeit):
df.shape
(60000, 2)
%%timeit -n10
_ = ['|'.join(s[i:]) for i, s in zip(df['occurrence'], df['string'].str.split('|'))]
67.9 ms ± 2.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit -n10 (using 'apply')
_ = df.apply(lambda x: '|'.join(x['string'].split('|')[x.occurrence:]), axis=1)
1.93 s ± 34.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

TA貢獻1712條經驗 獲得超3個贊
嘗試將您的 lambda 表達式更改為:
df.apply(lambda x: '|'.join(x['string'].split('|')[x.occurrence:]), axis=1)
如果你想要后面的元素(右側),你應該從出現作為索引開始。
結果:
0 8|9|10|11|12
1 12.2|13.6|14.7
2 1|2|3
3 4|5|6|7|8
4 5|6.2|7|8.1
5 1|2|3|4|5

TA貢獻1842條經驗 獲得超21個贊
一種有點非正統的方法:從中構建一個正則表達式df['occurrence']并使用它來匹配:
df['regex'] = df['occurrence'].map(lambda o: '^' + r'(?:[^|]*\|)'*o + r'(.*)$')
df['regex']
0 ^(?:[^|]*\|)(?:[^|]*\|)(?:[^|]*\|)(?:[^|]*\|)(...
1 ^(?:[^|]*\|)(?:[^|]*\|)(.*)$
2 ^(.*)$
3 ^(?:[^|]*\|)(?:[^|]*\|)(?:[^|]*\|)(.*)$
4 ^(?:[^|]*\|)(?:[^|]*\|)(?:[^|]*\|)(?:[^|]*\|)(...
5 ^(.*)$
Name: regex, dtype: object
現在只適用re.match于每一行:
df.apply(lambda row: re.match(row['regex'], row['string']).group(1), axis=1)
0 8|9|10|11|12
1 12.2|13.6|14.7
2 1|2|3
3 4|5|6|7|8
4 5|6.2|7|8.1
5 1|2|3|4|5
dtype: object
添加回答
舉報