Python,pandas:如何去除大于号

2 投票
4 回答
2317 浏览
提问于 2025-04-17 23:43

假设我有一个这样的示例数据表

from pandas import Series, DataFrame
df = DataFrame({'A':['1', '<2', '3']})

我想把A列的内容从字符串转换成整数。比如说,对于'<2',我想直接去掉'<'这个符号,然后在第二行放上1(因为1是小于2的最接近的整数)。有没有什么高效的方法可以做到这一点?这只是个例子。我实际处理的数据有成千上万行。感谢你们的帮助!

4 个回答

0
>>> import re
>>> df.applymap(lambda x: int(re.sub(r'[^0-9.]', '', x)))
   A
0  1
1  2
2  3

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

1

这里有另外两种方法可以做到这一点,希望对你有帮助!

from pandas import Series, DataFrame
df = DataFrame({'A':['1', '<2', '3']})

输出结果

df.A.str.strip('<').astype(int)
Out[1]:
0    1
1    2
2    3

这种方法特别适合你想要在数字中间去掉某个字符的时候(比如说,如果你有一个逗号之类的)。

df = DataFrame({'A':['1', '1,002', '3']})
df.A.str.replace(',', '').astype(int)

输出结果

Out[11]:
0       1
1    1002
2       3
Name: A, dtype: int64
1

你可以在数据表(DataFrame)上使用applymap这个方法,如果字符串中出现了"<"这个字符,就把它去掉。

df.applymap(lambda x: x.replace('<',''))

下面是处理后的结果:

   A
0  1
1  2
2  3
3

你可以使用 Series.apply 这个功能:

import pandas as pd
df = pd.DataFrame({'A':['1', '<2', '3']})
df['A'] = df['A'].apply(lambda x: int(x[1:])-1 if x.startswith('<') else int(x))
print(df.dtypes)
# A    int64
# dtype: object

这样会得到

print(df)
   A
0  1
1  1
2  3

[3 rows x 1 columns]

撰写回答