Python 3.x 将/Map函数应用于dataframe以检索新列
假设我有一个pandas数据框,其中的“path”列指定了图像文件的路径 我还有一个函数f,比如“get_info”,它进行api调用并输出“a”、“b”和“c” 现在我想将f应用于我的数据帧,作为回报,创建输出为“a”、“b”和“c”的新列。我希望在10行的垃圾中这样做,以保存中间结果(因为函数发出请求需要一些时间才能完成,并且数据帧有很多行) 我想要的输出可以是这样的数据帧:Python 3.x 将/Map函数应用于dataframe以检索新列,python-3.x,pandas,dataframe,apply,series,Python 3.x,Pandas,Dataframe,Apply,Series,假设我有一个pandas数据框,其中的“path”列指定了图像文件的路径 我还有一个函数f,比如“get_info”,它进行api调用并输出“a”、“b”和“c” 现在我想将f应用于我的数据帧,作为回报,创建输出为“a”、“b”和“c”的新列。我希望在10行的垃圾中这样做,以保存中间结果(因为函数发出请求需要一些时间才能完成,并且数据帧有很多行) 我想要的输出可以是这样的数据帧: xabc 35'路径1'[[一些列表][[一些列表]][[一些列表]] 1'路径2'楠楠楠楠 362“路径3”[[s
xabc
35'路径1'[[一些列表][[一些列表]][[一些列表]]
1'路径2'楠楠楠楠
362“路径3”[[some List][[some List]][[some List]]
首先,我尝试了以下代码:
df['a']=np.nan
df['b']=np.nan
df['c']=np.nan
for i in range(0, len(df),10):
try:
df[['a','b','c']].iloc[i:(i+10)]= df['path'].iloc[i:(i+10)].apply(get_info).apply(pd.Series)
except:
print("Unexpected error:", sys.exc_info()[1])
然而,这产生了一个数据帧,其中列“a”、“b”、“c”都只填充了NAN。但是,如果我只跑
df['path'].iloc[0:(0+10)].apply(get_info).apply(pd.Series)
输出与预期一致(具有列“a”、“b”、“c”的数据帧)
然后我试着:
df['a']=np.nan
df['b']=np.nan
df['c']=np.nan
for i in range(0, len(df),10):
try:
df['a'].iloc[i:(i+10)], df['b'].iloc[i:(i+10)], df['c'].iloc[i:(i+10)]\
= zip(*df['path'].iloc[i:(i+10)].map(get_info))
df.to_pickle('somepath')
except:
print("Unexpected error:", sys.exc_info()[i])
但是,对于这段代码,我得到了以下错误
TypeError: zip argument #1 must support iteration
IndexError: tuple index out of range
编辑:根据@pshep123的请求,函数代码如下:
def get_info(path):
data = open(path, 'rb')
retries =0
while retries < 2:
try:
# Execute the REST API call and get the response.
response = requests.request('POST', uri_base + '/detect', data=data, headers=headers, params=params)
faces = json.loads(response.text)
a=[]
b=[]
c=[]
for face in faces:
a.append(face['faceAttributes']['emotion']['anger'])
b.append(face['faceAttributes']['emotion']['contempt'])
c.append(face['faceAttributes']['emotion']['disgust'])
return a, b, c
except:
if retries <2:
time.sleep(60)
retries+=1
else:
return np.nan
return np.nan
def get_info(路径):
数据=打开(路径“rb”)
重试次数=0
当重试次数小于2次时:
尝试:
#执行RESTAPI调用并获取响应。
response=requests.request('POST',uri_base+'/detect',data=data,headers=headers,params=params)
faces=json.load(response.text)
a=[]
b=[]
c=[]
对于面中的面:
a、 附加(面部['faceAttributes']['emotion']['anger'])
b、 附加(脸['faceAttributes']['emotion']['Dispath'])
c、 附加(面部['faceAttributes']['emotion']['Abost'])
返回a、b、c
除:
如果重试部分问题:您的sys.exc_info()[i]
正在使用for
循环中的i
。您需要的是[1]
。另外,如果您包含transform\u x
函数,这样我们就可以看到输出是什么(或应该是什么)。感谢您的有用评论。我还包括了函数(重命名为“get_info”)@pshep123。现在有没有其他信息?