我有兩個數(shù)據(jù)框df1和df2:df1 = pd.DataFrame({"a" : [1,2,3,4,5,6,7,8,9,10,11,12], "b" : [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12], "t" : [1,2,3,4,5,6,7,8,9,10,11,12]})df1.index = [1,1,1,2,2,2,3,3,3,4,4,5]df2 = pd.DataFrame({"a" : [10,20,30], "b" : [-10,-20,-30]})df2.index = [2,3,4]它們看起來像這樣:df1 a b t1 1 -1 11 2 -2 21 3 -3 32 4 -4 42 5 -5 52 6 -6 63 7 -7 73 8 -8 83 9 -9 94 10 -10 104 11 -11 115 12 -12 12df2 a b2 10 -103 20 -204 30 -30所以 的列df2是的列的子集df1。我想將 的行df1與df2它們具有相同索引的行相乘,并且只保留由它們的索引之間的交集組成的行,即基本上ls_keep = []for i in range(len(df1)): for j in range(len(df2)): if df1.index[i] == df2.index[j]: df1.iloc[i]["a"] = df1.iloc[i]["a"] * df2.iloc[j]["a"] df1.iloc[i]["b"] = df1.iloc[i]["b"] * df2.iloc[j]["b"] ls_keep.append(i)df1 = df1.iloc[ls_keep]這給了我 a b t2 40 40 42 50 50 52 60 60 63 140 140 73 160 160 83 180 180 94 300 300 104 330 330 11此代碼按預期工作,但非常不專業(yè)且很長,以防只有兩列以上。有沒有辦法使用 的函數(shù)來優(yōu)化它pandas?
1 回答

牛魔王的故事
TA貢獻1830條經(jīng)驗 獲得超3個贊
首先過濾器僅匹配索引到新DataFrame的boolean indexing和isin,然后通過多mul用df2.columns在這兩個處理相同的列DataFrameS:
df11 = df1[df1.index.isin(df2.index)].copy()
df11[df2.columns] = df11[df2.columns].mul(df2)
print (df11)
a b t
2 40 40 4
2 50 50 5
2 60 60 6
3 140 140 7
3 160 160 8
3 180 180 9
4 300 300 10
4 330 330 11
添加回答
舉報
0/150
提交
取消