Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 修改dataframe列的字符串值_Python_Pandas_Dataframe - Fatal编程技术网

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)