如何将用户标识数组馈送到flickr.people.getInfo下载()?

2024-04-20 12:44:25 发布

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

我一直致力于提取flickr用户的位置(不是lat.和long。但个人的国家)使用他们的用户ID。我制作了一个由photoid、owner和其他几个列组成的dataframe(Here's the dataframe)。我的尝试是通过迭代dataframe中的owner列,将每个所有者提供给flickr.people.getInfo()查询。这是我的尝试

for index, row in df.iterrows():
     A=np.array(df["owner"])
for i in range(len(A)):
    B=flickr.people.getInfo(user_id=A[i])

不幸的是,结果只有一个。经过仔细检查,我发现它属于数据帧中的最后一个用户。我的数据框有250个观测值。我不知道我怎么能把别人挖出来。 感谢您的帮助。你知道吗


Tags: 数据用户iniddataframedffor国家
2条回答

实现这一点的标准方法是使用apply。这样会更有效率。你知道吗

import pandas as pd
import numpy as np

np.random.seed(0)

# A function to simulate the call to the API
def get_user_info(id):
    return np.random.randint(id, id + 10)

# Some test data
df = pd.DataFrame({'id': [0,1,2], 'name': ['Pierre', 'Paul', 'Jacques']})

# Here the call is made for each ID
df['info'] = df['id'].apply(get_user_info)

#    id     name  info
# 0   0   Pierre     5
# 1   1     Paul     1
# 2   2  Jacques     5

注意,写同样东西的另一种方法是

df['info'] = df['id'].map(lambda x: get_user_info(x))

似乎在遍历数据帧时忘记了存储结果。我没有使用API,但我认为这个代码段应该可以。你知道吗

result_dict = {}
for idx, owner in df['owner'].iteritems():
    result_dict[owner] = flickr.people.getInfo(user_id=owner)

结果存储在一个以用户id为键的听写器中。你知道吗

编辑:

因为它是一个JSON,所以可以使用read_json函数来解析结果。 示例:

result_list = []
for idx, owner in df['owner'].iteritems():
    result_list.appen(pd.read_json(json.dumps(flickr.people.get‌​Info(user_id=owner))‌​,orient=list))
    # you may have to set the orient parameter. 
    # Option are: 'split','records','index', Default is 'index'

注意:我把听写改成了列表,因为这样更方便

之后,您可以将生成的系列串联在一起,如下所示:

df = pd.concat(result_list, axis=1).transpose()

我添加了transpose(),因为您可能希望ID作为索引。 之后,您应该能够按“location”列进行排序。 希望有帮助。你知道吗

相关问题 更多 >