2017-04-17 62 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