![](/img/trans.png)
[英]Using pandas to look up the values of one column from the closest match between another column and multiple inputs
[英]Use a function to return multiple column outputs from specific column inputs using Pandas
我想通過應用從多個特定的現有列中獲取輸入的函數,將兩個新列添加到我的數據框中。
這是我的方法,可用於返回一列,但不能返回多列:
這是我的DataFrame:
d = {'a': [3,0,2,2],
'b': [0,1,2,3],
'c': [1,1,2,3],
'd': [2,2,1,3]}
df = pd.DataFrame(d)
我正在嘗試應用此功能:
def myfunc(a,b,c):
if a > 2 and b > 2:
print('condition 1',a,b)
return pd.Series((a,b))
elif a < 2 and c < 2:
print('condition 2',a,c)
return pd.Series((b,c))
else:
print('no condition')
return pd.Series((None,None))
像這樣:
df['e'],df['f'] = df.apply(lambda x: myfunc(x['a'],x['b'],x['c']),axis=1)
輸出:
no condition
no condition
condition 2 0 1
no condition
no condition
DataFrame結果:
如何輸入多列並取出多列?
當my_funct匹配時,您的函數將使用NAs
或2元組返回一個系列。
解決它的一種方法是返回Series,該序列將通過apply自動擴展:
def myfunc(col1,col2,col3):
if col1 == 'x' and col2 == 'y':
return pd.Series((col1,col2))
if col2 == 'a' and col3 == 'b':
return pd.Series(('yes','no'))
請注意使用雙括號將一個參數作為元組傳遞。 列表也可以。
問題在於分配,而不是myfunc
當您嘗試將數據框解壓縮為元組時,它將返回列標簽。 這就是為什么您得到所有東西的(0,1)
df['e'], df['f'] = pd.DataFrame([[8, 9]] * 1000000, columns=['Told', 'You'])
print(df)
a b c d e f
0 3 0 1 2 Told You
1 0 1 1 2 Told You
2 2 2 2 1 Told You
3 2 3 3 3 Told You
使用join
df.join(df.apply(lambda x: myfunc(x['a'],x['b'],x['c']),axis=1))
或pd.concat
pd.concat([df, df.apply(lambda x: myfunc(x['a'],x['b'],x['c']),axis=1)], axis=1)
都給
a b c d e f
0 3 0 1 2 NaN NaN
1 0 1 1 2 1.0 1.0
2 2 2 2 1 NaN NaN
3 2 3 3 3 NaN NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.