Pandas设置单个数据框格式
问题
有没有办法只格式化一个特定的数据框(dataframe)?
我见过一些例子是格式化单个数据框中的特定列(例子1),或者把整个pandas库设置成默认选项(例子2)。但是,我没有看到可以格式化特定数据框而不需要逐个列出每一列的选项。
设置
import pandas as pd
import numpy as np
# Setup first example
data = np.random.random((3,4))
df = pd.DataFrame(data)
print df
# 0 1 2 3
#0 0.384326 0.364187 0.084034 0.012376
#1 0.114784 0.298068 0.087634 0.828207
#2 0.255923 0.438617 0.820652 0.266964
例子1 - 更改单个数据框中特定列的格式
df[3] = df[3].map('${:,.2f}'.format)
print df
# 0 1 2 3
#0 0.384326 0.364187 0.084034 $0.01
#1 0.114784 0.298068 0.087634 $0.83
#2 0.255923 0.438617 0.820652 $0.27
例子2 - 更改所有pandas数据框的格式(包括新创建的)
pd.options.display.float_format = '${:,.2f}'.format
print(df)
# 0 1 2 3
#0 $0.38 $0.36 $0.08 $0.01
#1 $0.11 $0.30 $0.09 $0.83
#2 $0.26 $0.44 $0.82 $0.27
data2 = np.random.random((4,3))
df2 = pd.DataFrame(data2)
print df2
# 0 1 2
#0 $0.60 $0.37 $0.86
#1 $0.28 $0.06 $0.97
#2 $0.19 $0.68 $0.99
#3 $0.06 $0.88 $0.82
我在寻找一个像例子2那样的选项,不过它不会把格式应用到未来的数据框上。谢谢!
编辑 - 抱歉,我应该更清楚地说明格式化的内容。例子1是改变数据类型,而例子2则没有。我希望能避免在数据类型之间转换(如果可能的话)。例如,第一个例子是把浮点数转换成非空对象:
df.info()
#<class 'pandas.core.frame.DataFrame'>
#Int64Index: 3 entries, 0 to 2
#Data columns (total 4 columns):
#0 3 non-null float64
#1 3 non-null float64
#2 3 non-null float64
#3 3 non-null object
#dtypes: float64(3), object(1)
2 个回答
5
我觉得你最好的办法是给 to_string
函数传递一个格式化器。
In [283]: print df.to_string(float_format='${:,.2f}'.format)
0 1 2 3
0 $0.53 $0.01 $0.75 $0.61
1 $0.54 $0.33 $0.42 $0.47
2 $0.28 $0.67 $0.71 $0.53
不过这样做的话,格式化的效果不会保留在数据框里。你可以尝试做一些类似“猴子补丁”的操作,像这样。
In [286]: from functools import partial
In [287]: df.to_string = partial(df.to_string, float_format='${:,.2f}'.format)
In [288]: print df
0 1 2 3
0 $0.53 $0.01 $0.75 $0.61
1 $0.54 $0.33 $0.42 $0.47
2 $0.28 $0.67 $0.71 $0.53
4
你可以这样遍历每一列:
for i in range(len(df.columns)):
df[i] = df[i].map('${:,.2f}'.format)
或者你也可以这样做:
df.applymap('${:,.2f}'.format)