leo*_*fer 3 python dataframe pandas
在数据框中
\n\ndf = pd.DataFrame({'c1': ['c10:b', 'c11', 'c12:k'], 'c2': ['c20', 'c21', 'c22']})\n\n c1 c2\n0 c10:b c20\n1 c11 c21\n2 c12:k c22\n
Run Code Online (Sandbox Code Playgroud)\n\n我想修改 c1 列的字符串值,以便删除冒号之后(包括)的所有内容,因此最终结果如下:
\n\n c1 c2\n0 c10 c20\n1 c11 c21\n2 c12 c22\n
Run Code Online (Sandbox Code Playgroud)\n\n我试过切片
\n\ndf[\xe2\x80\x99c1\xe2\x80\x99].str[:df[\xe2\x80\x99c1\xe2\x80\x99].str.find(\xe2\x80\x99:\xe2\x80\x99)]\n
Run Code Online (Sandbox Code Playgroud)\n\n但它不起作用。我该如何实现这个目标?
\nreplace
与以下一起使用regex=True
:
df.replace(r'\\:.*', '', regex=True)\n
Run Code Online (Sandbox Code Playgroud)\n\n\n\n c1 c2\n0 c10 c20\n1 c11 c21\n2 c12 c22\n
Run Code Online (Sandbox Code Playgroud)\n\n要仅在单个列中替换此模式,请使用str
访问器:
df.c1.str.replace(r'\\:.*', '')\n
Run Code Online (Sandbox Code Playgroud)\n\n如果性能是一个问题,请使用列表理解而partition
不是pandas
字符串方法:
[i.partition(':')[0] for i in df.c1]\n# ['c10', 'c11', 'c12']\n
Run Code Online (Sandbox Code Playgroud)\n\n时间安排
\n\ndf = pd.concat([df]*10000)\n\n%timeit df.replace(r'\\:.*', '', regex=True)\n30.8 ms \xc2\xb1 340 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\n%timeit df.c1.str.replace(r'\\:.*', '')\n31.2 ms \xc2\xb1 449 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\n%timeit df['c1'].str.partition(':')[0]\n56.7 ms \xc2\xb1 269 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10 loops each)\n\n%timeit [i.partition(':')[0] for i in df.c1]\n4.2 ms \xc2\xb1 22.2 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 100 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n