【问题标题】:How Can I build a url from dataframe element?如何从数据框元素构建 url?
【发布时间】:2020-01-16 22:19:37
【问题描述】:

我为 ESPN 网站的团队编写了一个通用函数,其中包含两个元素 team_id 和 team_name 的数据框。 我想编写一个代码,它会根据给定的 team_id 和 team_name 生成一个自定义的 url。

Example : team_id = 2132 and team_name = Cincinnati Bearcats

下面是代码

def get_team_url(team_id, team_name):
   import pandas as pd

   df = pd.DataFrame(['team_id','team_name'])

   df['url'] = 'http://www.espn.com/college-football/team/roster/_/?id=' + df.iloc[0]+ '&team_name=' + 

   df.iloc[1]

    return df

当我为函数提供值时,我在 Jupiter 笔记本中遇到以下错误

当我在不同的 shell 中编写断言函数时:

assert team_url == 'https://www.espn.com/college-football/team/roster/_/id/2132/Cincinnati Bearcats'

然后我得到以下错误:

ValueError:DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python-3.x pandas dataframe jupyter-notebook data-science


    【解决方案1】:
    df['url'] = base_url + "?id=" + df['team_id'].astype(str) + "&team_name=" + df["team_name"]
    

    【讨论】:

    • 请不要只留下没有任何描述的代码
    【解决方案2】:

    定义变量,如team_id = 2132team_name = 'Cincinnati Bearcats'。 team_id 现在是int,team_name 现在是string。 那么你可以将这些参数传递给一个函数。

    def get_team_url(team_id, team_name): import pandas as pd df = pd.DataFrame([team_id',team_name]) df['url'] = 'http://www.espn.com/college-football/team/roster/_/?id=' +df.iloc[0].astype(str)+ '&team_name=' + df.iloc[1] return df

    我试过了,效果很好。

    >>> team_id = 2132
    >>> team_name = 'Cincinnati Bearcats'
    >>> def get_team_url(team_id, team_name):
    ...    import pandas as pd
    ...    df = pd.DataFrame([team_id,team_name])
    ...    df['url'] = 'http://www.espn.com/college-football/team/roster/_/?id=' + df.iloc[0].astype(str)+ '&team_name=' + df.iloc[1]
    ...    return df
    ... 
    >>> get_team_url(team_id,team_name)
    
                         0                                                url
    0                 2132  http://www.espn.com/college-football/team/rost...
    1  Cincinnati Bearcats                                                NaN
    

    【讨论】:

    • 是的,它可以工作,但我不喜欢这种安排。并且从您的输出中未创建 url,如果您单击它,它将无处可去。而且数据框对齐也不好..我希望 url 为 'espn.com/college-football/team/roster/_/id/2132/Cincinnati'
    • 我想要这个,最后得到了这个结果,它有点多余的代码,但是我想要这个实际的形式
    • 我认为添加到您的代码中会对您有所帮助。这就是为什么我稍微做了一些改变,但我猜其余的都是一样的
    猜你喜欢
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多