![](/img/trans.png)
[英]Pandas apply function to multindexed columns that takes columns (Series) as arguments
[英]How to apply a function on a series of columns, based on the values in a corresponding series of columns?
我有一個 df,其中有幾列,根據這些列中的值 (1-6),我想為其相應的列分配一個值 (0-1)。 我可以逐列進行,但希望將其設為單一功能。 下面是一些示例代碼:
import pandas as pd
df = pd.DataFrame({'col1': [1,3,6,3,5,2], 'col2': [4,5,6,6,1,3], 'col3': [3,6,5,1,1,6],
'colA': [0,0,0,0,0,0], 'colB': [0,0,0,0,0,0], 'colC': [0,0,0,0,0,0]})
(col1 對應 colA,col2 對應 colB,col3 對應 colC)
此代碼逐列工作:
df.loc[(df.col1 != 1) & (df.col1 < 6), 'colA'] = (df['colA']+ 1)
但我希望能夠有一個列列表,可以這么說,並讓它與另一個相對應。 像這樣的東西,(但實際上有效):
m = df['col1' : 'col3'] != 1 & df['col1' : 'col3'] < 6
df.loc[m, 'colA' : 'colC'] += 1
謝謝你!
想法是通過DataFrame.loc
過濾兩個DataFrame
s,然后通過掩碼過濾列並通過另一個df2
重命名列,最后僅將DataFrame.add
用於df.columns
:
df1 = df.loc[:, 'col1' : 'col3']
df2 = df.loc[:, 'colA' : 'colC']
d = dict(zip(df1.columns,df2.columns))
df1 = ((df1 != 1) & (df1 < 6)).rename(columns=d)
df[df2.columns] = df[df2.columns].add(df1)
print (df)
col1 col2 col3 colA colB colC
0 1 4 3 0 1 1
1 3 5 6 1 1 0
2 6 6 5 0 0 1
3 3 6 1 1 0 0
4 5 1 1 1 0 0
5 2 3 6 1 1 0
這是我會做的:
# split up dataframe
sub_df = df.iloc[:,:3]
abc = df.iloc[:,3:]
# make numpy array truth table
truth_table = (sub_df.to_numpy() > 1) & (sub_df.to_numpy() < 6)
# redefine abc based on numpy truth table
new_abc = pd.DataFrame(truth_table.astype(int), columns=['colA', 'colB', 'colC'])
# join the updated dataframe subgroups
new_df = pd.concat([sub_df, new_abc], axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.