簡體   English   中英

通過索引和列名稱數組切片Pandas數據幀

[英]Slice a Pandas dataframe by an array of indices and column names

我想用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]

在熊貓:

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相同的數據?

熊貓不直接支持這一點; 它可以,但問題是如何指定你想要坐標而不是不同的軸,例如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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM