从大数据帧中删除pandas中的列(从开始到结束)最有效的方法是什么?

2024-09-28 01:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从pandas数据帧的开头和结尾删除一些列。你知道吗

我的数据帧有397行和291列。我目前有此解决方案来删除前8列,但我还想删除最后的一些列:

SMPS_Data = SMPS_Data.drop(SMPS_Data.columns[0:8], axis=1)

我知道我可以重复这个步骤并删除最后几列,但我希望有一个更直接的方法来解决这个问题。你知道吗

我试过用

SMPS_Data = SMPS_Data.drop(SMPS_Data.columns[0:8,278:291], axis=1)

但它不起作用。你知道吗

另外,似乎.drop方法在某种程度上降低了控制台的响应速度,所以也许有更干净的方法来做到这一点?你知道吗


Tags: columns数据方法pandasdata结尾步骤解决方案
1条回答
网友
1楼 · 发布于 2024-09-28 01:32:35

如果要按列名删除列,可以使用^{}

drop_these = ['column_name1', 'column_name2', 'last_columns']
df = df.drop(columns=drop_these)

如果知道要按位置删除它们,可以使用^{}

df.iloc[:, 8:15]  # For columns 8-15
df.iloc[:, :-5]   # For all columns, except the last five
df.iloc[:. 2:-5]  # For all columns, except the first column, and the last five

有关更多信息,请参见索引和切片数据上的this documentation。你知道吗

相关问题 更多 >

    热门问题