簡體   English   中英

Python:從數據框中選擇多個相似的列

[英]Python: Selecting multiple similar columns from dataframe

我有一個數據框:

df:

    a21   b21   c21  a22   b22  a23  b23
1    2    2      2    4     5    7    7
2    2    2      2    4     5    7    7
3    2    2      2    4     5    7    7
4    2    2      2    4     5    7    7
5    2    2      2    4     5    7    7

我只想選擇具有'21''23'列,這樣我的輸出是:

df_output:

    a21   b21   c21   a23  b23
1    2    2      2     7    7
2    2    2      2     7    7
3    2    2      2     7    7
4    2    2      2     7    7
5    2    2      2     7    7

我可以使用以下代碼執行此操作:

df_21 = (df.loc[:, df.filter(like='21').columns])    
df_23 = (df.loc[:, df.filter(like='23').columns])

然后,我可以合並df_21df_23但是是否有一種有效的方法可以在一行代碼中執行相同的操作?

我們可以使用DataFrame.filter()方法:

In [38]: df.filter(regex=r'21|23')
Out[38]:
   a21  b21  c21  a23  b23
1    2    2    2    7    7
2    2    2    2    7    7
3    2    2    2    7    7
4    2    2    2    7    7
5    2    2    2    7    7

要么:

In [45]: df.loc[:, df.columns.str.contains(r'21|23')]
Out[45]:
   a21  b21  c21  a23  b23
1    2    2    2    7    7
2    2    2    2    7    7
3    2    2    2    7    7
4    2    2    2    7    7
5    2    2    2    7    7

您可以使用條件列表理解:

targets = ['21', '23']
df[[col for col in df if any(target in col for target in targets)]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM