如何在 Pandas 中获取浮点列的整数部分

Gop*_*dak 3 python numpy pandas

假设我有一个数据框 df 如下所示

    qty
0   1.300
1   1.909
Run Code Online (Sandbox Code Playgroud)

现在我只想提取 qty 列的整数部分,df 应该看起来像

   qty
0   1
1   1
Run Code Online (Sandbox Code Playgroud)

尝试使用 df['qty'].round(0) 但没有得到想要的结果,因为它将数字四舍五入到最接近的整数。

Java 有一个函数 intValue() 可以执行所需的操作。pandas 中是否有类似的功能?

jez*_*ael 5

通过Series.astype以下方式将值转换为整数:

df['qty'] = df['qty'].astype(int)
print (df)
   qty
0    1
1    1
Run Code Online (Sandbox Code Playgroud)

如果上面不起作用,则可能numpy.modf用于提取值之前.

a, b = np.modf(df['qty'])
df['qty'] = b.astype(int)
print (df)
   qty
0    1
1    1
Run Code Online (Sandbox Code Playgroud)

或者通过 split before .,但如果大型 DataFrame 应该很慢:

df['qty'] = b.astype(str).str.strip('.').str[0].astype(int)
Run Code Online (Sandbox Code Playgroud)

或使用numpy.floor

df['qty'] = np.floor(df['qty']).astype(int)
Run Code Online (Sandbox Code Playgroud)