gpt4 book ai didi

python - 如何在 pandas 中选择没有弃用 ix 的多列

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:55 25 4
gpt4 key购买 nike

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

最佳答案

是的,函数被称为Index.get_indexer并按名称列表返回列或索引的位置。

这样使用:

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

关于python - 如何在 pandas 中选择没有弃用 ix 的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com