能否使用loc选择列范围以及该范围之外的列? [英] Can you use loc to select a range of columns plus a column outside of the range?

查看:44
本文介绍了能否使用loc选择列范围以及该范围之外的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要从数据框中选择一系列列:将它们称为"column_1"至"column_60".我知道我可以像这样使用loc: df.loc [:,'column_1':'column_60'] 这将为我提供第1-60列中的所有行.

Suppose I want to select a range of columns from a dataframe: Call them 'column_1' through 'column_60'. I know I could use loc like this: df.loc[:, 'column_1':'column_60'] That will give me all rows in columns 1-60.

但是,如果我想要该范围的列再加上'column_81',该怎么办?不起作用: df.loc [:,'column_1':'column_60','column_81']

But what if I wanted that range of columns plus 'column_81'. This doesn't work: df.loc[:, 'column_1':'column_60', 'column_81']

它引发索引器过多"错误.还有另一种使用loc声明状态的方法吗?还是在这种情况下loc甚至是最好的功能?

It throws a "Too many indexers" error. Is there another way to state this using loc? Or is loc even the best function to use in this case?

非常感谢.

推荐答案

如何

df.loc[:, [f'column_{i}' for i in range(1, 61)] + ['column_81']]

df.reindex([f'column_{i}' for i in range(1, 61)] + ['column_81'], axis=1)

如果要填充缺少的列,则使用默认的 NaN 值.

if you want to fill missing columns, if there are, with default NaN values.

这篇关于能否使用loc选择列范围以及该范围之外的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆