【问题标题】:Extract Pandas Columns between two values提取两个值之间的 Pandas 列
【发布时间】:2020-04-18 18:32:56
【问题描述】:

我有如下数据。前 2 列是字符串和列 df[3:60] 的列名作为连续年份。如何将 2005 年:2010 年和 2015 年之间的所有列提取到所有内容中

Country Indicator 1960    1961  1962    1963.....
Aruba    US$      15678 156789  156790  156791
Afgha    US$      68239 78239   88239   98239
Angola   US$      45678 55678   65678   75678
Albania  US$      89345 99345   109345  119345
Andorra  US$      62790 72790   82790   92790
Arab     US$     12987  22987   32987   42987
UAE      US$      6047  16047   26047   36047


我尝试提取列索引

df.index.get_loc('2005') <- 45
df.index.get_loc('2010') <- 50
df.index.get_loc('2015') <- 55

df.iloc[:, [45:50,55:]]

以上代码显示错误。如何提取具有索引范围的多列

【问题讨论】:

  • 将变量col_range定义为col_range = list(range(2005, 2011))。现在使用 -df.loc[:, col_range],它会给你一个只有 2005...2010 列的数据框

标签: python pandas dataframe multiple-columns


【解决方案1】:

您可以使用np.r_:

a = df.columns.get_loc('2005')
b = df.columns.get_loc('2010')
c = df.columns.get_loc('2015')

df.iloc[:,np.r_[a-1:b,c-1:len(df.columns)]]

例子:

df = pd.DataFrame(columns=list('ab') +
                [*map(str,pd.date_range('2000','2021',freq='y').year)])
print(df)

Empty DataFrame
Columns: [a, b, 2000, 2001, 2002, 2003, 2004, 2005,
         2006, 2007, 2008, 2009, 2010, 2011, 2012, 
         2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
Index: []

print(df.iloc[:,np.r_[a-1:b,c-1:len(df.columns)]])

Empty DataFrame
Columns: [2005, 2006, 2007, 2008, 2009, 2010, 2015, 2016, 2017, 2018, 2019, 2020]
Index: []

【讨论】:

  • 这个解决方案非常优雅
【解决方案2】:

我认为@anky 使用np.r_ 是正确的方法并且非常灵活,这个答案只是一个替代方案,使用pandas 内置索引方法:

注意:我正在使用@anky 的示例数据框:

df = pd.DataFrame(columns=list('ab') +
                [*map(str,pd.date_range('2000','2021',freq='y').year)])

使用slice_indexer 获取感兴趣值的切片位置:

A = df.columns.slice_indexer('2005','2010')
A
slice(7, 13, None)
#if one entry is included, it includes the location of the last index
B = df.columns.slice_indexer('2015')
B
slice(17, 23, None)

添加 A 和 B 的 iloc 索引:

res = df.iloc[:,A] + df.iloc[:,B]
res
Index(['2005', '2006', '2007', '2008', '2009', '2010', '2015', '2016', '2017',
       '2018', '2019', '2020'],
      dtype='object')

还要注意@anky 的方法会更有效,因为 iloc 只被调用一次。同样,这只是对可用方法的一种玩弄

当然,你可以将np.r_与A和B的slices结合起来:

res = df.iloc[:,np.r_[A,B]]
res.columns
Index(['2005', '2006', '2007', '2008', '2009', '2010', '2015', '2016', '2017',
       '2018', '2019', '2020'],
      dtype='object')

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    相关资源
    最近更新 更多