如何在pandas中选择多个不推荐使用ix的列

2024-09-30 20:20:33 发布

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

在python中,对于packagepandas中的DataFrame中的数据切片,.ix已经从pandas 0.20.0中弃用。官方网站提供了另一种解决方案,可以使用.loc.iloc来进行混合选择(http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html)。索引可以帮助提取多行。相比之下,columns.get_loc列似乎最多只能选择一列。是否有一个替代函数可以使用.iloc以混合方式提取多个列?在


Tags: 数据orghttpdocsdataframepandas切片解决方案
1条回答
网友
1楼 · 发布于 2024-09-30 20:20:33

是的,函数名为^{},并按名称列表返回列或索引的位置。在

使用方法如下:

df = pd.DataFrame({
         'a':[4,5,4,5,5,4],
         'b':[7,8,9,4,2,3],
         'c':[1,3,5,7,1,0],
         'd':[5,3,6,9,2,4],
}, index=list('ABCDEF'))
print (df)
   a  b  c  d
A  4  7  1  5
B  5  8  3  3
C  4  9  5  6
D  5  4  7  9
E  5  2  1  2
F  4  3  0  4

cols = ['a','b','c']
df1 = df.iloc[1, df.columns.get_indexer(cols)]
print (df1)
a    5
b    8
c    3
Name: B, dtype: int64

df11 = df.iloc[[1], df.columns.get_indexer(cols)]
print (df11)
   a  b  c
B  5  8  3

idx = ['A','C']
df2 = df.iloc[df.index.get_indexer(idx), 2:]
print (df2)
   c  d
A  1  5
C  5  6

相关问题 更多 >