从datafram中的列中删除特定位置的数字

2024-04-27 03:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在熊猫数据帧中有一列df

import pandas as pd
s = {'id': [47035,460,23045,87068,8007,78096],
 'st': ['a', 'a', 'd', 'e', 'f', 'a']}
df = pd.DataFrame(s)

我想删除0(或任何其他数字,如果有的话),它只在列id的第三个位置。我怎么能这样做呢?你知道吗

所以在删除之后,列id中的值应该是4735、46234587688077896。你知道吗


Tags: 数据importiddataframepandasdfas数字
3条回答

IIUC公司

df.id.str[:2]+df.id.str[2].where(df.id.str[2]==0,'')+df.id.str[3:]
0    4735
1      46
2    2345
3    8768
4     807
5    7896
Name: id, dtype: object

使用str.slice_replace如下:

df.id.astype(str).str.slice_replace(2, 3, '')

Out[422]:
0    4735
1      46
2    2345
3    8768
4     807
5    7896
Name: id, dtype: object

一种方法是将它们转换为字符串并删除第三个字符,然后再转换回int:

s = {'id': [47035,460,23045,87068,8007,78096],
 'st': ['a', 'a', 'd', 'e', 'f', 'a']}
df = pd.DataFrame(s)

# convert to sting and strip away the middle third character then concat
df['id'] = (df['id'].astype(str).str[:2] + df['id'].astype(str).str[3:]).astype(int)

     id st
0  4735  a
1    46  a
2  2345  d
3  8768  e
4   807  f
5  7896  a

相关问题 更多 >