首页 > 解决方案 > Pandas DataFrame 的整数列中如何存在空格?

问题描述

我从他们自己的 csv 文件中加载了两个 dfs。它们是单独生成的,我无法控制。第一个似乎有空格,即使它是整数 dtype。

In: df1 = read_csv(file1.csv)
In: df2 = read_csv(file2.csv)

In: df1['key'].head().values
Out: array([    1,    10,   100,  1000, 10000], dtype=int64)
In: print(df1['key'].head().values) #using print()
Out: [    1    10   100  1000 10000]

In: df2['key'].head().values
Out: array([1, 2, 3, 4, 5], dtype=int64)
In: print(df1['key'].head().values) #using print()
Out: [1 2 3 4 5]

所以我不能在这个专栏中加入他们 - 没有匹配。但实际上似乎没有空格:

In: df1['key'].astype(str).head().values
Out: array(['1', '10', '100', '1000', '10000'], dtype=object)

并且使用.str.strip()和/或.str.replace(' ','')不起作用。这是有道理的,因为它可能没有传统的字符串空格。

In: df1['key'].astype(str).str.replace(' ','').astype(int).head().values
Out: array([    1,    10,   100,  1000, 10000], dtype=int64)

我什至不知道如何在谷歌上搜索这个。我要处理什么样的空白?我该如何清理它?谢谢你的帮助。

标签: pythonpandas

解决方案


正如@TYZ 所指出的,当打印值时,空格是由熊猫添加的,以使格式看起来不错。它不存储在数据框中的任何位置。要以这种方式显示事物,请pandas定义对象的__str__()方法。当 Python 将对象转换为类型时调用此方法,例如在解释器中显示对象或使用函数时。pandas.DataFramepandas.Seriesstrprint()

pandas将数据作为数组(来自.values)返回时,它是 a numpy.ndarrray,它还有一个__str__()用于漂亮打印的自定义方法。

例如:

In [1]: import pandas as pd

In [2]: df1 = pd.DataFrame( {'key':[    1,    10,   100,  1000, 10000]} )

In [3]: print(df1)
     key
0      1
1     10
2    100
3   1000
4  10000

数字自动右对齐,以便输出看起来不错。

In [4]: type(df1['key'].values)
Out[4]: numpy.ndarray

In [5]: df1['key'].values
Out[5]: array([    1,    10,   100,  1000, 10000], dtype=int64)

In [6]: print(df1['key'].values)
[    1    10   100  1000 10000]

.values属性返回 a numpy.ndarray,它也使用自定义__str__()方法进行格式化。

pandasnumpy.ndarray格式基于正在打印的内容。仅打印一位数字的数据框,无需额外填充。将多位数字附加到数据帧会导致打印的所有单位数字的填充长度与最长数字相等。此示例显示填充如何取决于正在打印的项目。

In [11]: df2 = pd.DataFrame( {'key':[1,2,3,4,5]} )

In [12]: print(df2['key'].values)
[1 2 3 4 5]

In [13]: print(df2.append({'key':1000}, ignore_index=True)['key'].values)
[   1    2    3    4    5 1000]

如果您想在没有漂亮格式的情况下显示数据,您可以随时将其转换为 Python list

In [21]: print(df1['key'].tolist())
[1, 10, 100, 1000, 10000]

推荐阅读