类型错误:使用 pandas apply 和 lambda 时,字符串索引必须是整数

Bru*_*yne 4 python lambda series dataframe pandas

我有一个数据框,一列是 URL,另一列是名称。我只是尝试添加第三列,该列接受 URL 并创建 HTML 链接。

该列newsSource具有链接名称和urlURL。对于数据框中的每一行,我想创建一个包含以下内容的列:

<a href="[the url]">[newsSource name]</a>
Run Code Online (Sandbox Code Playgroud)

尝试以下会引发错误

文件“C:\Users\AwesomeMan\Documents\Python\MISC\News Alerts\simple_news.py”,第 254 行,位于 df['sourceURL'] = df['url'].apply(lambda x: '{1} '.format(x, x[0]['newsSource']))
TypeError: 字符串索引必须是整数

df['sourceURL'] = df['url'].apply(lambda x: '<a href="{0}">{1}</a>'.format(x, x['source']))
Run Code Online (Sandbox Code Playgroud)

不过我x[colName]以前用过?下面的行工作正常,它只是创建一列源名称:

df['newsSource'] = df['source'].apply(lambda x: x['name'])
Run Code Online (Sandbox Code Playgroud)

为什么突然(对我来说“突然”)它说我无法访问索引?

jpp*_*jpp 5

pd.Series.apply只能访问单个系列,即您正在调用该方法的系列。换句话说,您提供的函数,无论它是命名的还是匿名的lambda,都只能访问df['source'].

要按行访问多个系列,您pd.DataFrame.apply需要axis=1

def return_link(x):
    return '<a href="{0}">{1}</a>'.format(x['url'], x['source'])

df['sourceURL'] = df.apply(return_link, axis=1)
Run Code Online (Sandbox Code Playgroud)

请注意,以这种方式传递整个系列会产生一定的开销;pd.DataFrame.apply只是一个薄弱的、低效的循环。

您可能会发现列表理解更有效:

df['sourceURL'] = ['<a href="{0}">{1}</a>'.format(i, j) \
                   for i, j in zip(df['url'], df['source'])]
Run Code Online (Sandbox Code Playgroud)

这是一个工作演示:

df = pd.DataFrame([['BBC', 'http://www.bbc.o.uk']],
                  columns=['source', 'url'])

def return_link(x):
    return '<a href="{0}">{1}</a>'.format(x['url'], x['source'])

df['sourceURL'] = df.apply(return_link, axis=1)

print(df)

  source                  url                              sourceURL
0    BBC  http://www.bbc.o.uk  <a href="http://www.bbc.o.uk">BBC</a>
Run Code Online (Sandbox Code Playgroud)