Python 修改dataframe列的字符串值
在数据帧中Python 修改dataframe列的字符串值,python,pandas,dataframe,Python,Pandas,Dataframe,在数据帧中 df = pd.DataFrame({'c1': ['c10:b', 'c11', 'c12:k'], 'c2': ['c20', 'c21', 'c22']}) c1 c2 0 c10:b c20 1 c11 c21 2 c12:k c22 我想修改列c1的字符串值,以便删除冒号后面(包括冒号)的所有内容,因此结果如下: c1 c2 0 c10 c20 1 c11 c21 2 c12 c22
df = pd.DataFrame({'c1': ['c10:b', 'c11', 'c12:k'], 'c2': ['c20', 'c21', 'c22']})
c1 c2
0 c10:b c20
1 c11 c21
2 c12:k c22
我想修改列c1的字符串值,以便删除冒号后面(包括冒号)的所有内容,因此结果如下:
c1 c2
0 c10 c20
1 c11 c21
2 c12 c22
我试过切片
df[’c1’].str[:df[’c1’].str.find(’:’)]
但它不起作用。如何实现这一点?使用
替换为regex=True
:
df.replace(r'\:.*', '', regex=True)
要仅在单个列中替换此模式,请使用str
访问器:
df.c1.str.replace(r'\:.*', '')
如果性能是一个问题,请使用列表理解和分区
而不是字符串方法:
[i.partition(':')[0] for i in df.c1]
# ['c10', 'c11', 'c12']
计时
[i.partition(':')[0] for i in df.c1]
# ['c10', 'c11', 'c12']
df = pd.concat([df]*10000)
%timeit df.replace(r'\:.*', '', regex=True)
30.8 ms ± 340 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit df.c1.str.replace(r'\:.*', '')
31.2 ms ± 449 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit df['c1'].str.partition(':')[0]
56.7 ms ± 269 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit [i.partition(':')[0] for i in df.c1]
4.2 ms ± 22.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)