gpt4 book ai didi

python - 为什么在 pandas dataframe 上使用 .apply 时会给出错误的结果?我的循环版本有效

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:01 25 4
gpt4 key购买 nike

我有两个 Pandas DataFrame:

  1. df_topics_temp 包含 一个带有 id 列的矩阵
  2. df_mapping 包含 idparentID 的映射

我正在尝试使用 df_mapping 中的 parentID 填充 df_topics_temp 中的 parent.id 列。

我已经写了一个使用循环的解决方案,尽管它非常麻烦。有用。我使用 pandas .applydf_topics_temp 的解决方案不起作用

解决方案 1(有效):


def isnan(value):
try:
import math
return math.isnan(float(value))
except:
return False

for x in range(0, df_topics_temp['id'].count()):
topic_id_loop = df_topics_temp['topic.id'].iloc[x]
mapping_row = df_mapping[df_mapping['id'] == topic_id_loop]
parent_id = mapping_row['parentId'].iloc[0]

if isnan(parent_id):
df_topics_temp['parent.id'].iloc[x] = mapping_row['id'].iloc[0]
else:
df_topics_temp['parent.id'].iloc[x] = topic_id_loop

解决方案 2(不起作用):


def map_function(x):
df_topics_temp = df_mapping.loc[df_mapping['id'] == x]
temp = df_topics_temp['parentId'].iloc[0]
return temp

df_topics_temp['parent.id'] = df_topics_temp['topic.id'].apply(map_function)

df_topics_temp.head()

第二个解决方案 (pandas .apply) 不会填充 df_topics_temp 中的 parent.id 列。

感谢您的帮助

更新 1

<ipython-input-68-a2e8d9a21c26> in map_function(row)
1 def map_function(row):
----> 2 row['parent.id'] = df_mapping.loc[df_mapping['id']==row['topic.id']]['parentId'].values[0]
3 return row

IndexError: ('index 0 is out of bounds for axis 0 with size 0', 'occurred at index 190999')

最佳答案

如果我理解正确的话,“apply”需要一行并返回一行。因此,您希望函数返回一行。你的返回一个值。例如:

#setting up the dataframes
import pandas as pd
import numpy as np
df1 = pd.DataFrame.from_dict({'name':['alice','bob'],'id':[1,2]})
mapping = pd.DataFrame.from_dict({'id':[1,2,3,4],'parent_id':[100,200,100,200]})

#mapping function
def f(row):
if any(mapping['id']==row['id']):
row['parent_id'] = mapping.loc[mapping['id']==row['id']]['parent_id'].values[0]
else: # missing value
row['parent_id'] = np.nan
return row

df1.apply(f,axis=1)

关于python - 为什么在 pandas dataframe 上使用 .apply 时会给出错误的结果?我的循环版本有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55391696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com