Skip to main content
 首页 » 编程设计

python之删除 pandas DataFrame 打印中的 `dtype: object`

2025年05月04日17shihaiming

这是我的代码:

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 

几乎完美,只是我想去掉“Name: Address, dtype: object”行。我已经尝试了一些东西,它不会在不弄乱其他所有内容的格式的情况下消失。

请您参考如下方法:

'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 

或者我重写你的函数

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]