Python 如何从单个pandas.apply()调用中形成乘法列?
我有一个函数,它返回一个由4项组成的元组 我有一个DataFrame,我想要的是通过在其中一列上应用函数,向我的DataFrame添加4个新列。怎么做 以下是我的尝试:Python 如何从单个pandas.apply()调用中形成乘法列?,python,pandas,Python,Pandas,我有一个函数,它返回一个由4项组成的元组 我有一个DataFrame,我想要的是通过在其中一列上应用函数,向我的DataFrame添加4个新列。怎么做 以下是我的尝试: a['w'], a['x'], a['y'], a['z'] = a["existing"].apply(lambda x: find_data_from_ip(x)) 但由于这是一个只有两行的测试数据帧,我得到了以下错误: ValueError:需要2个以上的值才能解包 您需要从函数返回系列: def find_data_f
a['w'], a['x'], a['y'], a['z'] =
a["existing"].apply(lambda x: find_data_from_ip(x))
但由于这是一个只有两行的测试数据帧,我得到了以下错误:
ValueError:需要2个以上的值才能解包
您需要从函数返回
系列
:
def find_data_from_ip(x):
tup = (1,2,3,4)
return (pd.Series(tup, index=['w','x','y','z']))
a = pd.DataFrame({'existing':[1,2,3]})
print (a)
a[['w','x','y','z']] = a["existing"].apply(lambda x: find_data_from_ip(x))
print (a)
existing w x y z
0 1 1 2 3 4
1 2 1 2 3 4
2 3 1 2 3 4
另一种解决方案是从元组列创建DataFrame
,然后再创建为原始:
def find_data_from_ip(x):
tup = (1,2,3,4)
return (tup)
a = pd.DataFrame({'existing':[1,2,3]})
#print (a)
print (a["existing"].apply(lambda x: find_data_from_ip(x)))
0 (1, 2, 3, 4)
1 (1, 2, 3, 4)
2 (1, 2, 3, 4)
Name: existing, dtype: object
a1 = pd.DataFrame.from_records(a["existing"].apply(lambda x: find_data_from_ip(x))
.values
.tolist(),
columns = ['w','x','y','z'])
print (a1)
w x y z
0 1 2 3 4
1 1 2 3 4
2 1 2 3 4
print (pd.concat([a,a1],axis=1))
existing w x y z
0 1 1 2 3 4
1 2 1 2 3 4
2 3 1 2 3 4