python - 从 Pandas 元组列表中选择行

标签 python pandas

我有一个像这样的 DataFrame:

In [140]: df.head()
Out[140]: 
   user  brand  action  nthday
0   767   3961       0      51
1   767   3961       2      51
2   767   3961       2      51
3   767   3961       0      51
4   767   3961       0      51

我想选择带有这样一个元组列表的行:

mylist = [(767, 3961), (768, 4201),...]

我可以做我想做的事:

# ( (767, 3961, 0, 51), ... )
intermediate_ = ( tuple(r) for (i,r) in df.iterrows() if tuple(r)[:2] in set(mylist))

# reconstruct a DataFrame
subdf = DataFrame(intermediate_, columns = ['user', 'brand', 'action', ..])

这可行,但笨拙且缓慢。 pandas 中推荐的方式是什么?

最佳答案

只需将感兴趣的列设置为索引,排序,使用.loc

以创建框架为例

In [8]: df = DataFrame(np.random.randn(12,1),index=pd.MultiIndex.from_product([list(range(3)),list(range(4))],names=['foo','bar']))

In [10]: df.reset_index()
Out[10]: 
    foo  bar         0
0     0    0 -0.225873
1     0    1 -0.275865
2     0    2 -1.324766
3     0    3 -0.607122
4     1    0 -1.465992
5     1    1 -1.582276
6     1    2 -0.718533
7     1    3 -1.904252
8     2    0  0.588496
9     2    1 -1.057599
10    2    2  0.388754
11    2    3 -0.940285

In [11]: x = df.reset_index()

In [12]: df2 = x.set_index(['foo','bar']).sort_index()

In [13]: df2
Out[13]: 
                0
foo bar          
0   0   -0.225873
    1   -0.275865
    2   -1.324766
    3   -0.607122
1   0   -1.465992
    1   -1.582276
    2   -0.718533
    3   -1.904252
2   0    0.588496
    1   -1.057599
    2    0.388754
    3   -0.940285

用元组选择

In [14]: df2.loc[[(0,2),(2,0),(2,3)]]
Out[14]: 
                0
foo bar          
0   2   -1.324766
2   0    0.588496
    3   -0.940285

关于python - 从 Pandas 元组列表中选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24064739/

相关文章:

Python Pandas 从另一个数据帧更新数据帧值

python - 如何向 plotly express 条形图添加一条线

python - 使用 pd.read_clipboard 读取打印精美/格式化的数据框?

python - 尝试从 Twitter API 解析数据

python - multiprocessing.pool 中的错误组参数目前必须为 None

python - 取消转义字符串中的字符串

python - 计算 Python/pandas 数组中的连续正值

python - 计算字符串中的字符串

python - Tkinter Matplotlib,后端冲突?

java - 测量 Google App Engine 中的任务队列成本