在 pandas 中将对象转换为字符串

Convert object to string in pandas

我在 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 吗?

您可以将庞大的数据帧拆分成块,例如,您可以通过此方法来决定块的大小:

def splitDataFrameIntoSmaller(df, chunkSize = 10000): 
    listOfDf = list()
    numberChunks = len(df) // chunkSize + 1
    for i in range(numberChunks):
        listOfDf.append(df[i*chunkSize:(i+1)*chunkSize])
    return listOfDf

有了块之后,您可以分别在每个块上应用您的函数。

您可以测试字符串 isdigit and then use the boolean mask to convert those rows only in a vectorised manner and use 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