如何“选择不同"?跨越 pandas 中的多个数据框列? [英] How to "select distinct" across multiple data frame columns in pandas?
问题描述
我正在寻找一种等效于sql的方法
I'm looking for a way to do the equivalent to the sql
从dataframe_table选择SELECT col1,col2"
"SELECT DISTINCT col1, col2 FROM dataframe_table"
pandas sql比较中没有关于"distinct"的任何信息
The pandas sql comparison doesn't have anything about "distinct"
.unique()仅适用于单个列,因此我想可以合并这些列,或将它们放在列表/元组中并进行比较,但这似乎是熊猫应该以更原生的方式进行的操作.
.unique() only works for a single column, so I suppose I could concat the columns, or put them in a list/tuple and compare that way, but this seems like something pandas should do in a more native way.
我是否缺少明显的东西,还是没有办法做到?
Am I missing something obvious, or is there no way to do this?
推荐答案
You can use the drop_duplicates
method to get the unique rows in a DataFrame:
In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})
In [30]: df
Out[30]:
a b
0 1 3
1 2 4
2 1 3
3 2 5
In [32]: df.drop_duplicates()
Out[32]:
a b
0 1 3
1 2 4
3 2 5
如果您只想使用某些列来确定唯一性,则还可以提供subset
关键字参数.参见文档字符串.
You can also provide the subset
keyword argument if you only want to use certain columns to determine uniqueness. See the docstring.
这篇关于如何“选择不同"?跨越 pandas 中的多个数据框列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!