我一直在处理从CSV导入的数据。Pandas将一些列更改为浮点数,所以现在这些列中的数字显示为浮点数!但是,我需要将它们显示为整数或不带逗号。是否有方法将它们转换为整数或不显示逗号?


当前回答

要修改浮点数输出,可以这样做:

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

其他回答

虽然这里有很多选择, 还可以使用字典转换特定列的格式

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

这是更改特定列的数据格式以进行快速数据分析的一种有用且非常快速的方法。

扩展@Ryan G提到的pandas. datafame .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. datafframe .astype文档:

错误:{' raise ', ' ignore '},默认' raise ' 控制对所提供的dtype的无效数据引发异常。 Raise:允许抛出异常 Ignore:抑制异常。错误时返回原始对象 0.20.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

要修改浮点数输出,可以这样做:

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

这是一个快速的解决方案,如果你想转换更多的列的熊猫。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 ""。