2017-04-17 92 views
1

這裏是我的代碼:刪除`D型:object`在大熊貓數據幀打印

def boba_recs(lat, lng): 
    f1 = pd.read_csv("./boba_final.csv") 
    user_loc = Point(lng, lat) # converts user lat/long to point object 
    # makes dataframe of distances between each boba place and the user loc 
    f1['Distance'] = [user_loc.distance(Point(xy)) for xy in zip(f1.Longitude, f1.Lat)] 
    # grabs the three smallest distances 
    boba = f1.nsmallest(3, 'Distance').set_index('Name') # sets index to name 
    return(": " + boba['Address']) 

這將返回:

Name 
Coco Bubble Tea   : 129 E 45th St New York, NY 10017 
Gong Cha     : 75 W 38th St, New York, NY 10018 
Smoocha Tea & Juice Bar  : 315 5th Ave New York, NY 10016 
Name: Address, dtype: object 

近乎完美,除了我想擺脫「名稱:地址,dtype:object「行。我已經嘗試了一些東西,它不會消除其他所有格式的混亂。

回答

3

'Address'pd.Series'Name'的名稱索引

嘗試的名字:

s.rename_axis(None).rename(None) 

Coco Bubble Tea   : 129 E 45th St New York, NY 10017 
Gong Cha     : 75 W 38th St, New York, NY 10018 
Smoocha Tea & Juice Bar  : 315 5th Ave New York, NY 10016 
dtype: object 

或者我會重寫你的樂趣ction

def boba_recs(lat, lng): 
    f1 = pd.read_csv("./boba_final.csv") 
    user_loc = Point(lng, lat) # converts user lat/long to point object 
    # makes dataframe of distances between each boba place and the user loc 
    f1['Distance'] = [user_loc.distance(Point(xy)) for xy in zip(f1.Longitude, f1.Lat)] 
    # grabs the three smallest distances 
    boba = f1.nsmallest(3, 'Distance').set_index('Name') # sets index to name 
    return(": " + boba['Address']).rename_axis(None).rename(None) 

如果你想有一個字符串

def boba_recs(lat, lng): 
    f1 = pd.read_csv("./boba_final.csv") 
    user_loc = Point(lng, lat) # converts user lat/long to point object 
    # makes dataframe of distances between each boba place and the user loc 
    f1['Distance'] = [user_loc.distance(Point(xy)) for xy in zip(f1.Longitude, f1.Lat)] 
    # grabs the three smallest distances 
    boba = f1.nsmallest(3, 'Distance').set_index('Name') # sets index to name 
    temp = (": " + boba['Address']).rename_axis(None).__repr__() 
    return temp.rsplit('\n', 1)[0] 
+0

是的,我試過這個,但它仍然有dtype:object部分。 – lc2958

+0

當你返回一個'pd.Series'時,它會在你的屏幕上顯示''__repr__'方法返回的字符串。作爲描述的一部分,該方法被編寫爲在末尾返回'dtype'。我對你的問題是,你想要返回格式正確的字符串嗎?或者你想返回一個熊貓系列對象?如果你想要熊貓系列對象,那麼你將不得不忍受描述中的'dtype'。 – piRSquared

+0

正確格式化字符串,它並不一定是一系列 – lc2958

2

這不是一排。這是對您正在打印的數據的描述。嘗試只打印.values,你會看到。

[Coco Bubble Tea   : 129 E 45th St New York, NY 10017 
Gong Cha     : 75 W 38th St, New York, NY 10018 
Smoocha Tea & Juice Bar  : 315 5th Ave New York, NY 10016] 

更新基於您的評論:

print(pd.DataFrame(your_series)) 
Name 
Coco Bubble Tea   : 129 E 45th St New York, NY 10017 
Gong Cha     : 75 W 38th St, New York, NY 10018 
Smoocha Tea & Juice Bar  : 315 5th Ave New York, NY 10016 
+0

再次,並非完全理想的,因爲那將是一個列表,而不是返回字符串。當然,我可以遍歷它,但如果有什麼我可以直接從數據框格式化,我非常喜歡。 – lc2958

+0

@ lc2958更新瞭解決您的問題的答案 – Grr