如何在熊猫中将逗号分隔的值转换为整数

时间:2020-07-05 04:51:59

标签: python pandas

我在熊猫中有以下数据框。

  order_id    no
  1           1,234,450,445.00 
  2           1,234,450,446.00
  3           1,234,450,447.00

我想将no列转换为整数。以下是我想要的数据框。

  order_id    no
  1           1234450445 
  2           1234450446
  3           1234450447

执行dtypes时,它显示为float64

我尝试关注

df['no'] = (pd.to_numeric(df['no'].str.replace(',',''), errors='coerce'))

如何在熊猫中将其转换为整数?

2 个答案:

答案 0 :(得分:3)

这是一种方法,请先进行浮点运算:

df['no'].str.replace(',','').astype(float).astype(int)

输出:

0    1234450445
1    1234450446
2    1234450447
Name: no, dtype: int64

或先切片'.00',然后将所有行结尾:

df['no'].str.strip('.00').str.replace(',','').astype(int)

答案 1 :(得分:0)

希望可以帮助您。

default

import pandas as pd
import numpy as np
df['no'] = df['no'].astype(str).apply(lambda x: "".join(x.split(","))).astype(np.float64).astype(np.int64)