【问题标题】:Pandas selecting discontinuous columns from a dataframe熊猫从数据框中选择不连续的列
【发布时间】:2015-03-23 22:17:43
【问题描述】:

我正在使用以下内容从数据框组合中选择特定列,我想将其引入新的数据框。个人选择工作正常,例如:comb.ix[:,0:1],但是当我尝试使用 + 组合它们时,我得到了一个糟糕的结果,第一个选择 ([:,0:1]) 卡在了最后数据框和原始 col 1 中包含的值在出现在行尾时被清除。获取我想要的列的正确方法是什么? (我会包含示例数据,但如您所见,列太多......这就是我尝试这样做的原因)

comb.ix[:,0:1]+comb.ix[:,17:342]

【问题讨论】:

  • 您是否要按列添加它们?试试pd.concat([comb.ix[:,0:1],comb.ix[:,17:342]], axis=1)
  • 宾果游戏,完成并回答,感谢您的快速响应!
  • 这可能有点可爱,但也可以做类似的事情:comb.ix[:,[0]+range(17,343)]
  • 我想我们也可以使用 numpy.r_ 参考:stackoverflow.com/questions/41256648/…

标签: python pandas


【解决方案1】:

NumPy 有一个不错的模块,名为 r_,允许您使用现代 DataFrame 选择界面 iloc 来解决它:

df.iloc[:, np.r_[0:1, 17:342]]

我相信这是一个更优雅的解决方案。

它甚至支持更复杂的选择:

df.iloc[:, np.r_[0:1, 5, 16, 17:342:2, -5:]]

【讨论】:

  • 这是最好的答案。
【解决方案2】:

我最近只是通过附加范围来解决它

r1 = pd.Series(range(5))
r2 = pd.Series([10,15,20])
final_range = r1.append(r2)
df.iloc[:,final_range]

然后您将获得 0:5 和 10、15、20 的列。

【讨论】:

    【解决方案3】:

    如果您想连接 df 列的子选择,请使用 pd.concat:

    pd.concat([comb.ix[:,0:1],comb.ix[:,17:342]], axis=1)
    

    只要索引匹配,就会正确对齐。

    感谢@iHightower,您还可以通过传递标签进行子选择:

    pd.concat([df.ix[:,'Col1':'Col5'],df.ix[:,'Col9':'Col15']],a‌​xis=1)
    

    请注意,.ix 将在未来的版本中被弃用,以下应该可以工作:

    In [115]:
    df = pd.DataFrame(columns=['col' + str(x) for x in range(10)])
    df
    
    Out[115]:
    Empty DataFrame
    Columns: [col0, col1, col2, col3, col4, col5, col6, col7, col8, col9]
    Index: []
    
    In [118]:
    pd.concat([df.loc[:, 'col2':'col4'], df.loc[:, 'col7':'col8']], axis=1)
    ​
    Out[118]:
    Empty DataFrame
    Columns: [col2, col3, col4, col7, col8]
    Index: []
    

    或者使用iloc:

    In [127]:
    pd.concat([df.iloc[:, df.columns.get_loc('col2'):df.columns.get_loc('col4')], df.iloc[:, df.columns.get_loc('col7'):df.columns.get_loc('col8')]], axis=1)
    
    Out[127]:
    Empty DataFrame
    Columns: [col2, col3, col7]
    Index: []
    

    请注意,iloc 切片是打开/关闭的,因此不包括结束范围,因此如果要包含它,您必须在感兴趣的列之后找到该列:

    In [128]:
    pd.concat([df.iloc[:, df.columns.get_loc('col2'):df.columns.get_loc('col4')+1], df.iloc[:, df.columns.get_loc('col7'):df.columns.get_loc('col8')+1]], axis=1)
    
    Out[128]:
    Empty DataFrame
    Columns: [col2, col3, col4, col7, col8]
    Index: []
    

    【讨论】:

    • 您也可以像这样使用带有 .ix 的标签...例如pd.concat([df.ix[:,'Col1':'Col5'],df.ix[:,'Col9':'Col15']],axis=1)
    • @ihightower 感谢您的建议,我已经更新了答案,还展示了如何使用lociloc 来实现这一点,因为.ix 将来会被弃用
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2019-06-29
    • 2018-07-14
    相关资源
    最近更新 更多