将浮点数的数据框转换为熊猫中的整数?

时间:2019-10-09 20:27:06

标签: python pandas

如何将熊猫数据框的每个数字元素转换为整数?我没有在网上看到任何有关此操作的文档,这令人惊讶,因为Pandas非常受欢迎...

3 个答案:

答案 0 :(得分:3)

如果您有一个整数数据框,只需直接使用astype

df.astype(int)

否则,请先使用select_dtypes选择数字列。

df.select_dtypes(np.number).astype(int)

df = pd.DataFrame({'col1': [1.,2.,3.,4.], 'col2': [10.,20.,30.,40.]})

   col1  col2
0   1.0  10.0
1   2.0  20.0
2   3.0  30.0
3   4.0  40.0

>>> df.astype(int)

   col1  col2
0     1    10
1     2    20
2     3    30
3     4    40

答案 1 :(得分:1)

您可以将apply用于此目的:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':np.arange(1.0, 20.0), 'B':np.arange(101.0, 120.0)})
print(df)
       A      B
0    1.0  101.0
1    2.0  102.0
2    3.0  103.0
3    4.0  104.0
4    5.0  105.0
5    6.0  106.0
6    7.0  107.0
7    8.0  108.0
8    9.0  109.0
9   10.0  110.0
10  11.0  111.0
11  12.0  112.0
12  13.0  113.0
13  14.0  114.0
14  15.0  115.0
15  16.0  116.0
16  17.0  117.0
17  18.0  118.0
18  19.0  119.0

df2 = df.apply(lambda a: [int(b) for b in a])
print(df2)

     A    B
0    1  101
1    2  102
2    3  103
3    4  104
4    5  105
5    6  106
6    7  107
7    8  108
8    9  109
9   10  110
10  11  111
11  12  112
12  13  113
13  14  114
14  15  115
15  16  116
16  17  117
17  18  118
18  19  119

一种更好的方法是在系列级别更改类型:

for col in df.columns:
    if df[col].dtype == np.float64:
        df[col] = df[col].astype('int')

print(df)

     A    B
0    1  101
1    2  102
2    3  103
3    4  104
4    5  105
5    6  106
6    7  107
7    8  108
8    9  109
9   10  110
10  11  111
11  12  112
12  13  113
13  14  114
14  15  115
15  16  116
16  17  117
17  18  118
18  19  119

答案 2 :(得分:1)

尝试一下:

column_types = dict(df.dtypes)
for column in df.columns:
    if column_types[column] == 'float64':
        df[column] = df[column].astype('int')
        df[column] = df[column].apply(lambda x: int(x))