2017-10-18 92 views
-1

我試圖將pandas中的查詢輸出從一系列格式轉換爲字符串格式。 的功能是以下(黃金*是列)將熊貓系列輸出轉換爲字符串

def try_three(): 
    import numpy as np 
    nz=df[(df["Gold"]>0) & (df["Gold.1"]>0) & (df["Gold.2"]>0)] 
    nz["average"]=((nz["Gold"])-(nz["Gold.1"]))/(nz["Gold.2"]) 
    return nz.where(nz["average"]==np.max(nz["average"])).dropna()["ID"] 

輸出是

Country 
Bulgaria BUL 
Name: ID, dtype: object 

其中國家是索引的名稱和BUL是ID字段的值。 我已經嘗試添加.astype(str)來獲取國家或ID的名稱,但沒有成功。如果我在前面加上「len」,我會得到答案1,所以我認爲有一些類似的東西,就像將字符串轉換爲輸出一樣簡單。

+1

,不顯示任何樣品數據-1 –

回答

1

如果輸出始終爲1元Series(因爲只有一個max)使用Series.item

nz.where(nz["average"]==np.max(nz["average"])).dropna()["ID"].item() 

但是我f可能的多個最大值,然後如果失敗。


所以是更多鈔票返回列表或從列表中加入string

nz.where(nz["average"]==np.max(nz["average"])).dropna()["ID"].tolist() 

或者:

', '.join(nz.where(nz["average"]==np.max(nz["average"])).dropna())["ID"].tolist() 

如果想一般的解決辦法:

a = nz.where(nz["average"]==np.max(nz["average"])).dropna()["ID"] 

if len(a) == 1: 
    return a.item() 
else: 
    return ', '.join(a) # a.tolist() 
1

IIUC你想在系列的第一個元素(ID列):

df['ID'].iat[0] 

演示:

In [77]: df = pd.DataFrame({'ID':['BUL']}, index=['Bulgaria']).rename_axis('Country') 

In [78]: df 
Out[78]: 
      ID 
Country 
Bulgaria BUL 

In [79]: df['ID'] 
Out[79]: 
Country 
Bulgaria BUL 
Name: ID, dtype: object 

In [80]: df['ID'].iat[0] 
Out[80]: 'BUL' 
+0

這不是我正在尋找的,因爲我想要更一般的東西。儘管如此,你的回答也很有幫助。還感謝我的代碼縮進。 –

相關問題