在Pandas面板中选择行

时间:2015-07-02 03:48:54

标签: python pandas

有没有办法从Pandas面板中选择行?

例如,在以下示例中,我可以跨数据框获取Job ==“B”的所有行吗?在常规数据框架中,我知道我可以使用

执行此操作
  

df1 [df1 [“job”] ==“A”]

但我不确定如何在没有循环的Pandas面板中执行此操作。

df1 = pd.DataFrame({"job":["A", "B", "C", "D"],"date":["DateA1", "DateB1", "DateC1", "DateD1"]})
df2 = pd.DataFrame({"job":["B", "C", "D", "E"],"date":[ "DateB2", "DateC2", "DateD2", "DateE2"]})
p = pd.Panel({"df1":df1, "df2":df2})

我的问题可能与此问题重复

Boolean Masking in Panels

1 个答案:

答案 0 :(得分:1)

使用2D df而不是3D面板可能更方便(至少对我来说:-))。

df1 = pd.DataFrame({"job":["A", "B", "C", "D"],"date":["DateA1", "DateB1", "DateC1", "DateD1"]})
df2 = pd.DataFrame({"job":["B", "C", "D", "E"],"date":[ "DateB2", "DateC2", "DateD2", "DateE2"]})
p = pd.Panel({"df1":df1, "df2":df2})

frame = p.to_frame()

Out[12]: 
                df1     df2
major minor                
0     date   DateA1  DateB2
      job         A       B
1     date   DateB1  DateC2
      job         B       C
2     date   DateC1  DateD2
      job         C       D
3     date   DateD1  DateE2
      job         D       E


res = frame.unstack('minor').stack(level=0)

Out[13]: 
minor        date job
major                
0     df1  DateA1   A
      df2  DateB2   B
1     df1  DateB1   B
      df2  DateC2   C
2     df1  DateC1   C
      df2  DateD2   D
3     df1  DateD1   D
      df2  DateE2   E


res.loc[res['job'] == 'B', :]

Out[14]: 
minor        date job
major                
0     df2  DateB2   B
1     df1  DateB1   B