我有一個tempdf 和 aa dflst。將temp來自dflst. 該dflst有len個動態的,我的問題棱時len(dflst)>=4。所有 DF(temp 和 dflst 中的所有 DF)都有帶真/假值的列和帶數字的 ap 列
重新創建資料的代碼:
#making temp df
var_cols=['a', 'b', 'c', 'd']
temp = pd.DataFrame(list(itertools.product([False, True], repeat=len(var_cols))), columns=var_cols)
#makinf dflst
df0=pd.DataFrame(list(itertools.product([False, True], repeat=len(['a', 'b']))), columns=['a', 'b'])
df0['p']= np.random.randint(1, 5, df0.shape[0])
df1=pd.DataFrame(list(itertools.product([False, True], repeat=len(['c', 'd']))), columns=['c', 'd'])
df1['p']= np.random.randint(1, 5, df1.shape[0])
df2=pd.DataFrame(list(itertools.product([False, True], repeat=len(['a', 'c', ]))), columns=['a', 'c'])
df2['p']= np.random.randint(1, 5, df2.shape[0])
df3=pd.DataFrame(list(itertools.product([False, True], repeat=len(['d']))), columns=['d'])
df3['p']= np.random.randint(1, 5, df3.shape[0])
dflst=[df0, df1, df2, df3]
我想合并 dflst 中的 dfs,以便將來自 dflst 中的 dfs 的 'p'col 值轉換為 temp df,在兩者之間具有兼容值的行中。
我目前正在使用 pd.merge 進行如下操作:
for df in dflst:
temp = temp.merge(df, on=list(df)[:-1], how='right')
但這會導致 df 對不同的列具有相同的名稱,當dflst有 4 個或更多 dfs 時..我知道這是由于suffix合并。但它會產生列索引問題。
如何在temp迭代添加的新列上具有唯一名稱?
uj5u.com熱心網友回復:
我不完全明白你想要什么,但 IIUC:
for i, df in enumerate(dflst):
temp = temp.merge(df.rename(columns={'p': f'p{i}'}),
on=df.columns[:-1].tolist(), how='right')
print(temp)
# Output:
a b c d p0 p1 p2 p3
0 False False False False 4 2 2 1
1 False True False False 3 2 2 1
2 False False True False 4 3 4 1
3 False True True False 3 3 4 1
4 True False False False 3 2 2 1
5 True True False False 3 2 2 1
6 True False True False 3 3 1 1
7 True True True False 3 3 1 1
8 False False False True 4 4 2 3
9 False True False True 3 4 2 3
10 False False True True 4 1 4 3
11 False True True True 3 1 4 3
12 True False False True 3 4 2 3
13 True True False True 3 4 2 3
14 True False True True 3 1 1 3
15 True True True True 3 1 1 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387657.html
