使用.apply将函数的输出应用于两列

2024-05-08 18:06:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,它接受一个地址并输出两个值:坐标(以列表形式)和结果(无论地理编码是否成功)。这很好,但是由于数据以列表的形式返回,因此我必须根据该列表的索引分配新列,这样可以工作,但会返回一个警告:

A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy.

编辑:为了清楚起见,我想我从那个页面了解到我应该使用.loc访问嵌套值。我的问题是更倾向于直接从一个函数生成两列,而不是稍后必须挖掘信息的解决方法。在

我想知道解决这些问题的正确方法,因为我在这个项目中遇到过两次这样的问题。在

问题的实际细节并不重要,因此这里有一个简单的例子来说明我是如何解决这个问题的:

^{pr2}$

因为这会在df列中生成一个嵌套列表,所以我将其提取到新列中,如下所示:

df['coordinates'] = None
df['gps_status'] = None

for index, row in df.iterrows():
    df['coordinates'][index] = df['output'][index][0]
    df['gps_status'][index] = df['output'][index][1]

我再次得到警告:

A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

如有任何关于正确方法的建议,我们将不胜感激。在


Tags: theto方法in警告pandasdf列表
2条回答

通常您希望避免iterrows(),因为一次对整个列进行操作会更快。您可以将输出结果直接分配给新列。在

import pandas as pd

def geo(x):
    return x*2, x*3

df = pd.DataFrame({'address':[1,2,3]})

output = df['address'].apply(geo)

df['a'] = [x[0] for x in output]
df['b'] = [x[1] for x in output]

给你

^{pr2}$

没有复制警告。在

函数应该返回一个序列:

def geo(address):
    location = geocode(address)
    result = location.result
    coords = location.coords
    return pd.Series([coords, result], ['coordinates', 'gps_status'])

df['output'] = df['address'].apply(geo)

也就是说,这可能更好地写成merge。在

相关问题 更多 >