我一直在处理从 CSV 导入的数据。 Pandas 将某些列更改为浮点数,因此现在这些列中的数字显示为浮点数!但是,我需要将它们显示为整数或不带逗号。有没有办法将它们转换为整数或不显示逗号?
df.col = df.col.astype(int)
df = df.astype(int)
要修改浮点输出,请执行以下操作:
df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df
Out[33]:
a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000
pd.options.display.float_format = '{:,.0f}'.format
df
Out[35]:
a
0 0
1 1
2 2
3 3
4 4
使用 pandas.DataFrame.astype(<type>)
函数来操作列 dtype。
>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
A B C D
0 0.542447 0.949988 0.669239 0.879887
1 0.068542 0.757775 0.891903 0.384542
2 0.021274 0.587504 0.180426 0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
A B C D
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
编辑:
处理缺失值:
>>> df
A B C D
0 0.475103 0.355453 0.66 0.869336
1 0.260395 0.200287 NaN 0.617024
2 0.517692 0.735613 0.18 0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
A B C D
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
考虑以下数据框:
>>> df = pd.DataFrame(10*np.random.rand(3, 4), columns=list("ABCD"))
>>> print(df)
... A B C D
... 0 8.362940 0.354027 1.916283 6.226750
... 1 1.988232 9.003545 9.277504 8.522808
... 2 1.141432 4.935593 2.700118 7.739108
使用列名列表,使用 applymap()
更改多个列的类型:
>>> cols = ['A', 'B']
>>> df[cols] = df[cols].applymap(np.int64)
>>> print(df)
... A B C D
... 0 8 0 1.916283 6.226750
... 1 1 9 9.277504 8.522808
... 2 1 4 2.700118 7.739108
或者对于带有 apply()
的单列:
>>> df['C'] = df['C'].apply(np.int64)
>>> print(df)
... A B C D
... 0 8 0 1 6.226750
... 1 1 9 9 8.522808
... 2 1 4 2 7.739108
ValueError: ('cannot convert float NaN to integer', u'occurred at index <column_name>')
df['C'] = df['C'].dropna().apply(np.int64)
将所有浮点列转换为 int
>>> df = pd.DataFrame(np.random.rand(5, 4) * 10, columns=list('PQRS'))
>>> print(df)
... P Q R S
... 0 4.395994 0.844292 8.543430 1.933934
... 1 0.311974 9.519054 6.171577 3.859993
... 2 2.056797 0.836150 5.270513 3.224497
... 3 3.919300 8.562298 6.852941 1.415992
... 4 9.958550 9.013425 8.703142 3.588733
>>> float_col = df.select_dtypes(include=['float64']) # This will select float columns only
>>> # list(float_col.columns.values)
>>> for col in float_col.columns.values:
... df[col] = df[col].astype('int64')
>>> print(df)
... P Q R S
... 0 4 0 8 1
... 1 0 9 6 3
... 2 2 0 5 3
... 3 3 8 6 1
... 4 9 9 8 3
如果您想将 pandas.DataFrame
的更多列从浮点数转换为整数,同时考虑到您可以具有 NaN 值的情况,这是一个快速的解决方案。
cols = ['col_1', 'col_2', 'col_3', 'col_4']
for col in cols:
df[col] = df[col].apply(lambda x: int(x) if x == x else "")
我尝试使用 else x)
和 else None)
,但结果仍然是浮点数,所以我使用了 else ""
。
""
应用于 col
中的所有值
扩展@Ryan G 提到的 pandas.DataFrame.astype(<type>)
方法的用法,可以使用 errors=ignore
参数仅转换那些不产生错误的列,这显着简化了语法。显然,忽略错误时应该小心,但对于这项任务,它非常方便。
>>> df = pd.DataFrame(np.random.rand(3, 4), columns=list('ABCD'))
>>> df *= 10
>>> print(df)
... A B C D
... 0 2.16861 8.34139 1.83434 6.91706
... 1 5.85938 9.71712 5.53371 4.26542
... 2 0.50112 4.06725 1.99795 4.75698
>>> df['E'] = list('XYZ')
>>> df.astype(int, errors='ignore')
>>> print(df)
... A B C D E
... 0 2 8 1 6 X
... 1 5 9 5 4 Y
... 2 0 4 1 4 Z
来自 pandas.DataFrame.astype 文档:
错误:{'raise', 'ignore'}, default 'raise' 控制在提供的 dtype 的无效数据上引发异常。 raise : 允许引发异常 ignore : 抑制异常。出错时返回原始对象 版本 0.20.0 中的新对象。
需要转换为 int 的列也可以在字典中提及,如下所示
df = df.astype({'col1': 'int', 'col2': 'int', 'col3': 'int'})
>>> import pandas as pd
>>> right = pd.DataFrame({'C': [1.002, 2.003], 'D': [1.009, 4.55], 'key': ['K0', 'K1']})
>>> print(right)
C D key
0 1.002 1.009 K0
1 2.003 4.550 K1
>>> right['C'] = right.C.astype(int)
>>> print(right)
C D key
0 1 1.009 K0
1 2 4.550 K1
使用“Int64”支持 NaN
astype(int) 和 astype('int64') 无法处理缺失值(numpy int)
astype('Int64') 可以处理缺失值(pandas int)
df['A'] = df['A'].astype('Int64') # capital I
这假设您希望将缺失值保留为 NaN。如果您打算估算它们,您可以先fillna
as Ryan suggested。
“Int64”(大写 I)的示例
如果浮点数已经四舍五入,只需使用 astype: df = pd.DataFrame({'A': [99.0, np.nan, 42.0]}) df['A'] = df['A'].astype(' Int64') # A # 0 99 # 1
笔记
'Int64' 是 Int64Dtype 的别名: df['A'] = df['A'].astype(pd.Int64Dtype()) # 与 astype('Int64') 相同
Sized/signed aliases are available: lower bound upper bound 'Int8' -128 127 'Int16' -32,768 32,767 'Int32' -2,147,483,648 2,147,483,647 'Int64' -9,223,372,036,854,775,808 9,223,372,036,854,775,807 'UInt8' 0 255 'UInt16' 0 65,535 'UInt32' 0 4,294,967,295 'UInt64' 0 18,446,744,073,709,551,615
在问题的文本中解释说数据来自csv。所以,我认为在读取数据时而不是之后进行转换的显示选项与主题相关。
在数据框中导入电子表格或 csv 时,“仅整数列”通常会转换为浮点数,因为 excel 将所有数值存储为浮点数以及底层库的工作方式。
当使用 read_excel 或 read_csv 读取文件时,有几个选项可以避免导入后转换:
参数 dtype 允许传递列名和目标类型的字典,例如 dtype = {"my_column": "Int64"}
参数转换器可用于传递进行转换的函数,例如将 NaN 更改为 0。 converters = {"my_column": lambda x: int(x) if x else 0}
参数 convert_float 会将“整数浮点数转换为 int(即 1.0 –> 1)”,但要注意像 NaN 这样的极端情况。此参数仅在 read_excel 中可用
为了在现有数据框中进行转换,其他评论中已经给出了几种替代方案,但是由于 v1.0.0 版 pandas 对这种情况有一个有趣的功能:convert_dtypes,即“使用支持 pd.NA 的 dtypes 将列转换为可能的最佳 dtypes。 "
例如:
In [3]: import numpy as np
In [4]: import pandas as pd
In [5]: df = pd.DataFrame(
...: {
...: "a": pd.Series([1, 2, 3], dtype=np.dtype("int64")),
...: "b": pd.Series([1.0, 2.0, 3.0], dtype=np.dtype("float")),
...: "c": pd.Series([1.0, np.nan, 3.0]),
...: "d": pd.Series([1, np.nan, 3]),
...: }
...: )
In [6]: df
Out[6]:
a b c d
0 1 1.0 1.0 1.0
1 2 2.0 NaN NaN
2 3 3.0 3.0 3.0
In [7]: df.dtypes
Out[7]:
a int64
b float64
c float64
d float64
dtype: object
In [8]: converted = df.convert_dtypes()
In [9]: converted.dtypes
Out[9]:
a Int64
b Int64
c Int64
d Int64
dtype: object
In [10]: converted
Out[10]:
a b c d
0 1 1 1 1
1 2 2 <NA> <NA>
2 3 3 3 3
pandas
>= 1.0 时需要查看的答案。非常感谢!
虽然这里有很多选项,您也可以使用字典转换特定列的格式
Data = pd.read_csv('Your_Data.csv')
Data_2 = Data.astype({"Column a":"int32", "Column_b": "float64", "Column_c": "int32"})
print(Data_2 .dtypes) # Check the dtypes of the columns
这是更改特定列的数据格式以进行快速数据分析的有用且非常快速的方法。
不定期副业成功案例分享
df.a = df.a.astype(float)
?这是否会复制(不确定如何使用astype()
的copy
参数)?无论如何要更新“就地”类型?DF.({'200': {'#': 354, '%': 0.9971830985915493}, '302': {'#': 1, '%': 0.0028169014084507044}})
注意 # 转换为浮点数,它们是行,而不是列。因为每个都是一个只能存储一个统一类型的Series
?dtype
的意图是什么?如果是dtype
,那么您需要将这些列创建为dtype
object
,以便允许混合,否则我的建议是只使用浮点数,在进行比较时使用np.isclose
#
应该保持整数,而%
通常是浮点数。