【问题标题】:Select multiple columns by labels in pandas not all in order在熊猫中按标签选择多列,而不是全部按顺序
【发布时间】:2019-07-20 10:34:16
【问题描述】:

我想从 pandas 数据框中选择一组列,但其中只有一些列是按顺序排列的。 例如,我想写这样的东西:

df.loc[:,['a','2001':'2040']]

这里也有人问过类似的问题,但答案没有帮助:Select multiple columns by labels (pandas)

就我而言,手动执行此操作太麻烦了。正则表达式是可能的,但很复杂,因为切片是面向数字而不是面向文本的。那么最简单的方法是什么?

【问题讨论】:

  • 也许使用范围来创建列列表? col_list=[str(i) for i in range(2001,2040)] 然后根据需要附加其他元素?然后 df.loc[:,col_list]`?

标签: python pandas


【解决方案1】:

您可以使用列表推导:

In [11]: df.columns
Out[11]: Index(['a', '2001', '2002', '2040', '2041'], dtype='object')

In [12]: [c for c in df.columns if c == "a" or c.isdigit() and 2001 <= int(c) <= 2040 ]
Out[12]: ['a', '2001', '2002', '2040']

In [13]: df[[c for c in df.columns if c == "a" or c.isdigit() and 2001 <= int(c) <= 2040 ]]

【讨论】:

  • 谢谢你,这很完美,很有启发性。
猜你喜欢
  • 2015-05-28
  • 1970-01-01
  • 2019-01-27
  • 2016-12-14
  • 2013-02-03
  • 1970-01-01
相关资源
最近更新 更多