python - pandas DataFrame/Series 值格式化问题

标签 python pandas

举个例子:

df = pd.DataFrame(np.arange(6).reshape(3, 2), columns=list('ab'))
print(df)

   a  b
0  0  1
1  2  3
2  4  5

比如说,我想选择列 'a' == 0 的行,并且我知道在我的数据框中只有一行满足此条件。

df1 = df.loc[df['a'] == 0]
print(df1)
   a  b
0  0  1
type(df1)
pandas.core.frame.DataFrame

df2 = df.loc[0]
print(df2)
a    0
b    1
Name: 0, dtype: int32
type(df2)
pandas.core.series.Series

如您所见,df1 是一个 DataFrame 实例,但 df2 是一个 Series,尽管 df1 只有一行。

现在,当我尝试格式化 df1 的值时,出现问题:

print('{:.2f}'.format(df1['a']))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-92-62c2a3e8dbc0> in <module>()
----> 1 print('{:.2f}'.format(df1['a']))

TypeError: unsupported format string passed to Series.__format__

但是打印df2的值是可以的。

print('{:.2f}'.format(df2['a']))
0.00

我明白这是因为 df1 是一个 DataFramedf1['a'] 将是一个 Series >,但传递给 format() 函数的参数需要其他值 比一个 Series 对象。所以我试图尴尬地绕过这个:

print('{:.2f}'.format(df1['a'].values[0]))
0.00

这里有没有更高效、更费力的方法?

最佳答案

如果要将数据类型更改为str,可以使用:

df = df[df['a'] == 0].astype(str)

结果打印(df):

   a  b
0  0  1

数据类型print(df.dtypes):

a    object
b    object
dtype: object

如果要应用字符串格式,可以使用:

df = df[df['a'] == 0].applymap('{:,.2f}'.format)

结果打印(df):

      a     b
0  0.00  1.00

数据类型print(df.dtypes):

a    object
b    object
dtype: object

下一个解决方案不会更改数据。

pattern = '{:,.2f}'.format
print df.to_string(formatters={'a': pattern, 'b': pattern})

输出:

     a    b
0 0.00 1.00
1 2.00 3.00
2 4.00 5.00

关于python - pandas DataFrame/Series 值格式化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44095339/

相关文章:

Python 优化 : Using vector technique to find power of each matrix in an numpy array

python - 如何交换 pandas 数据框上的索引和值

python - Pandas .cut VS df.describe()

python - 我想使用 Python 检查 sheet1 中某个列上的值是否也存在于 sheet2 上

python - SQLAlchemy 预加载集合大小/计数

python - 消息 : Error: Polling for changes failed: NetworkError when attempting to fetch resource while downloading file through Selenium and FirefoxProfile

c++ - C/Python API 不执行函数

python - Python中的日期时间减法是非对称的?

python - 在分组数据框上创建新列

python - 使用平均值填充 pandas 数据框中的缺失值