让我举一个例子:大熊猫据帧/系列值格式问题
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
说,我要选择与列“一” == 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
只有一行。
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
值:
现在,当我尝试格式化的df1
值出现问题。
print('{:.2f}'.format(df2['a']))
0.00
据我所知,这是因为df1
是DataFrame
,df1['a']
将是一个Series
,但传递给format()
函数的参数预计比Series
对象以外的东西 。所以我试图走动这个笨拙的:
print('{:.2f}'.format(df1['a'].values[0]))
0.00
有没有反正这是更有效率和pythnoic在这里?
你们是不是要格式化所有值作为字符串?或转换为浮动? –