Skip to main content
 首页 » 编程设计

python之Pandas :沿特定列切片后,获取 "values"而不返回整个数据帧

2024年12月31日6lhb25

这是正在发生的事情:

df = pd.read_csv('data') 
 
important_region = df[df.columns.get_loc('A'):df.columns.get_loc('C')] 
 
important_region_arr = important_region.values 
 
print(important_region_arr) 

问题来了:

print(important_region.shape) 
output: (5,30) 
 
print(important_region_arr.shape) 
output: (5,30) 
 
print(important_region) 
output: my columns, in the panda way 
 
print(important_region_arr) 
output: first 5 rows of the dataframe 

如何在为我的列建立索引后转换到 numpy 数组?

或者,我可以从一开始就转换为 numpy,然后在 numpy 中运行切片操作。但是,这在 pandas 中是如何完成的?

请您参考如下方法:

下面介绍了如何使用特定列对数据集进行切片。 loc 使您可以访问行和列组。 、之前的代表行和之后的列。如果指定了 :,则表示所有行。

data.loc[:,'A':'C'] 

更多理解请看documentation .