【问题标题】:Filter Subset Pandas Dataframe by rows and columns按行和列过滤子集 Pandas Dataframe
【发布时间】:2021-09-05 10:00:40
【问题描述】:

我有以下数据框:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.array(([1,2,3], [1,2,3], [1,2,3], [4,5,6])), 
                  columns=['one','two','three'])

#BelowI am sub setting by rows and columns. But I want to have more than just one column. 
#In this case Column 'One' and 'two'
small=df[df.one==1].one

这里有什么替代方案?

【问题讨论】:

  • small=df[df.one==1][["one", "two"]]

标签: python pandas filter subset multiple-columns


【解决方案1】:

你可以使用loc:

df = pd.DataFrame(np.array(([1,2,3], [1,2,3], [1,2,3], [4,5,6])), 
              columns=['one','two','three'])

small=df.loc[df.one==1, ["one", "two"]]
# >    one two
#    0  1   2
#    1  1   2
#    2  1   2

loc 的第一个元素是想要的行;第二个是通缉列。如此处所示,它允许屏蔽和索引。

【讨论】:

  • 谢谢。这很好用。但是哪种方法更有效,为什么?您在上面指出的那个或 df[df.one==1][['one','two']]
  • 从时间性能的角度来看,两种方法都非常接近(相差在 5% 以内)。一个有趣的区别是loc 允许您对列进行切片,如下所示:df.loc[df.one==1, "one":"three"]
  • 我的错,他们甚至没有接近。 loc 实际上在大型数据帧上要快几倍。
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 2019-04-29
  • 1970-01-01
  • 2012-07-06
  • 2020-06-07
相关资源
最近更新 更多