gpt4 book ai didi

python - 将 pandas 中的对象转换为字符串

转载 作者:行者123 更新时间:2023-12-01 03:16:55 26 4
gpt4 key购买 nike

我在 pandas 数据框中有变量,其值如下

print (df.xx)

1 5679558
2 (714) 254
3 0
4 00000000
5 000000000
6 00000000000
7 000000001
8 000000002
9 000000003
10 000000004
11 000000005

print (df.dtypes)
xx object

我如下所示,以便将其转换为 num

try:
print df.xx.apply(str).astype(int)
except ValueError:
pass

我确实尝试过这样

tin.tin = tin.tin.to_string().astype(int)

但这给了我 MemoryError,因为我有 3M 行。

有人可以帮助我剥离特殊字符并将其转换为 int64 吗?

最佳答案

您可以测试字符串 isdigit 是否有效然后使用 bool 掩码仅以矢量化方式转换这些行并使用 to_numeric参数errors='coerce':

In [88]:
df.loc[df['xxx'].str.isdigit(), 'xxx'] = pd.to_numeric(df['xxx'], errors='coerce')
df

Out[88]:
xxx
0 5.67956e+06
1 (714) 254
2 0
3 0
4 0
5 0
6 1
7 2
8 3
9 4
10 5

关于python - 将 pandas 中的对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com