我想使用一个产生多个输出的函数在现有的熊猫数据框中创建多个新列。
例如,说我有这个测试函数,它输出2件事:
def testfunc (TranspoId, LogId):
thing1 = TranspoId + LogId
thing2 = LogId - TranspoId
return thing1, thing2
我可以将这些返回的输出赋予两个不同的变量,如下所示:
Thing1,Thing2 = testfunc(4,28)
print(Thing1)
print(Thing2)
我尝试通过以下方式对数据框执行此操作:
data = {'Name':['Picard','Data','Guinan'],'TranspoId':[1,2,3],'LogId':[12,14,23]}
df = pd.DataFrame(data, columns = ['Name','TranspoId','LogId'])
print(df)
df['thing1','thing2'] = df.apply(lambda row: testfunc(row.TranspoId, row.LogId), axis=1)
print(df)
我想要的是这样的东西:
data = {'Name':['Picard','Data','Guinan'],'TranspoId':[1,2,3],'LogId':[12,14,23], 'Thing1':[13,16,26], 'Thing2':[11,12,20]}
df = pd.DataFrame(data, columns=['Name','TranspoId','LogId','Thing1','Thing2'])
print(df)
在现实世界中,函数的工作量很大,而且我无法运行两次,每次将新变量添加到df一次。
我已经为此打了几个小时。任何见解将不胜感激。
答案 0 :(得分:1)
我相信最好的方法是更改顺序并创建可与Series一起使用的功能。
import pandas as pd
# Create function that deals with series
def testfunc (Series1, Series2):
Thing1 = Series1 + Series2
Thing2 = Series1 - Series2
return Thing1, Thing2
# Create df
data = {'Name':['Picard','Data','Guinan'],'TranspoId':[1,2,3],'LogId':[12,14,23]}
df = pd.DataFrame(data, columns = ['Name','TranspoId','LogId'])
# Apply function
Thing1,Thing2 = testfunc(df['TranspoId'],df['LogId'])
print(Thing1)
print(Thing2)
# Assign new columns
df = df.assign(Thing1 = Thing1)
df = df.assign(Thing2 = Thing2)
# print df
print(df)
答案 1 :(得分:1)
您的函数应返回一个序列,该序列将一次计算出新列。然后,您可以使用pandas.apply()添加新字段。
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}
输出:
import pandas as pd
df = pd.DataFrame( {'TranspoId':[1,2,3], 'LogId':[4,5,6]})
def testfunc(row):
new_cols = pd.Series([
row['TranspoId'] + row['LogId'],
row['LogId'] - row['TranspoId']])
return new_cols
df[['thing1','thing2']] = df.apply(testfunc, axis = 1)
print(df)