python - 按索引和列名数组对 Pandas 数据框进行切片

标签 python numpy pandas dataframe slice

我正在寻找使用 pandas 数据框复制 numpy 数组的行为。我想传递一个索引数组和列名,并获取在相应索引和列名中找到的对象列表。

import pandas as pd
import numpy as np

在 numpy 中:

array=np.array(range(9)).reshape([3,3])
print array
print array[[0,1],[0,1]]

[[0 1 2]
 [3 4 5]
 [6 7 8]]

[0 4]

在 Pandas 中:

prng = pd.period_range('1/1/2011', '1/1/2013', freq='A')
df=pd.DataFrame(array,index=prng)
print df

      0  1  2
2011  0  1  2
2012  3  4  5
2013  6  7  8

df[[2011,2012],[0,1]]

预期输出:

[0 4]

我应该如何切片此数据框以使其返回与 numpy 相同的值?

最佳答案

Pandas 不直接支持这个;它可以,但问题是如何指定你想要坐标而不是不同的轴,例如df.iloc[[0,1],[0,1]] 表示 给我第 0 行和第 1 行以及第 0 列和第 1 列。

也就是说,你可以这样做:

你更新了问题并说你想从索引值开始

In [19]: row_indexer = df.index.get_indexer([Period('2011'),Period('2012')])

In [20]: col_indexer = df.columns.get_indexer([0,1])

In [21]: z = np.zeros(df.shape,dtype=bool)

In [22]: z[row_indexer,col_indexer] = True

In [23]: df.where(z)
Out[23]: 
       0   1   2
2011   0 NaN NaN
2012 NaN   4 NaN
2013 NaN NaN NaN

虽然这看起来更容易(这些是位置)

In [63]: df.values[[0,1],[0,1]]
Out[63]: array([0, 4])

或者这个;因为 Period 索引将从字符串中正确切片(此处不要使用整数)

In [26]: df.loc['2011',0]
Out[26]: 0

In [27]: df.loc['2012',1]
Out[27]: 4

关于python - 按索引和列名数组对 Pandas 数据框进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23686561/

相关文章:

python - 高级 Python 正则表达式 : how to evaluate and extract nested lists and numbers from a multiline string?

python - pandas如何通过一行生成多行

python - Subprocess 语句在 python 控制台中有效,但在 Serverdensity 插件中无效?

python - Numpy:洗牌元素的子集

Python Popen卡住

python - 如何迭代行并根据同一行中其他字段的内容查询特定字段?

python - 无法使用 python 3.10 启动 Airflow Web 服务器

Python numpy 数组的列加法与移位

python - 我需要在第 n 个索引处插入一行,该行将对其下方的所有行进行求和

python - 在python,selenium中切换帧的函数