讓我舉一個例子:大熊貓據幀/系列值格式問題
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在這裏?
你們是不是要格式化所有值作爲字符串?或轉換爲浮動? –