我有多個(gè)數(shù)據(jù)框,我想過濾每個(gè)數(shù)據(jù)框,以便每個(gè) df 只保留由單詞“總體”組成的列。我有以下 for 循環(huán),但它沒有與手動(dòng)執(zhí)行相同的效果 [又名 y15 = y15.filter(like='Overall')]。pit_dfs = [y15,y16,y17]for i in pit_dfs: i = i.filter(like='Overall')可復(fù)制的例子:y15 = pd.DataFrame({'Col1-Overall': ['a','b','c','d'], 'Col2': ['a','b','c','d'], 'Col3': ['a','b','c','d'], 'Col4': ['a','b','c','d']})y16 = pd.DataFrame({'Col1-Overall': ['a','b','c','d'], 'Col2': ['a','b','c','d'], 'Col3': ['a','b','c','d'], 'Col4': ['a','b','c','d']})y17 = pd.DataFrame({'Col1-Overall': ['a','b','c','d'], 'Col2': ['a','b','c','d'], 'Col3': ['a','b','c','d'], 'Col4': ['a','b','c','d']})預(yù)期輸出:y15+--------------+| Col1-Overall |+--------------+| a |+--------------+| b |+--------------+| c |+--------------+| d |+--------------+y16+--------------+| Col1-Overall |+--------------+| a |+--------------+| b |+--------------+| c |+--------------+| d |+--------------+y17+--------------+| Col1-Overall |+--------------+| a |+--------------+| b |+--------------+| c |+--------------+| d |+--------------+我知道這是一個(gè)簡單的例子,但在過去的一個(gè)小時(shí)里我一直在瀏覽 Stack,但找不到類似的例子。我缺少什么?謝謝!
2 回答

紫衣仙女
TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
循環(huán)中的變量不是指針,因此您不會(huì)更改實(shí)際的數(shù)據(jù)幀。
你可以這樣做(我沒有測試過):
pit_dfs = [y15,y16,y17,y18,y19]
for idx in range(len(pit_dfs)):
? ? pit_dfs[idx] = pit_dfs[idx].filter(like='Overall')

湖上湖
TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
這是一個(gè)替代方案:
pit_dfs = [y15,y16,y17,y18,y19]
def filter_cols_like(df, like):
cols_not_like = [col for col in df.columns if like not in col]
df.drop(columns=cols_not_like,inplace=True)
for i in pit_dfs:
filter_cols_like(i,like='Overall')
添加回答
舉報(bào)
0/150
提交
取消