[英]Select DataFrame rows where columns are greater than values in a Series
[英]Select rows from DataFrame where ID count is greater than X
我有一个Dataframe,其中包含一个ID。 此ID代表一个人,可以多次出现:
col_id col2 col3 col4....
row1 1
row2 1
row3 2
row4 3
row5 3
row6 3
row7 1
row8 7
我需要返回一个新的数据帧,其中ID列的value_counts大于2,例如2。
新数据框:
col_id col2 col3 col4....
row1 1
row2 1
row3 3
row4 3
row5 3
row6 1
此新数据框包含ID计数仅大于2的行。
编辑
从这里我需要按ID分隔数据。 理想情况下,我想要一个解决方案,其中每个ID都有一个数据帧:
数据帧1
col_id col2 col3 col4....
r1 1
r2 1
r3 1
数据帧2
col_id col2 col3 col4....
r1 2
r2 2
r3 2
数据框3
col_id col2 col3 col4....
r1 3
r2 3
r3 3
是否可以将这些连接到一个大型数据框中? 所以我可以有一个名为'index'的新列,它包含ID == 1,ID == 2等的行:
index
1 col_id col2 col3 col4....
r1 1
r2 1
r3 1
index
2 col_id col2 col3 col4....
r1 2
r2 2
r3 2
index
3 col_id col2 col3 col4....
r1 3
r2 3
r3 3
对于具有与原始DataFrame相同大小的Series
,请将GroupBy.transform
与GroupBy.size
一起使用,因此可以通过boolean indexing
进行过滤:
df = df[df.groupby('col_id')['col_id'].transform('size') > 2]
print (df)
col_id
row1 1
row2 1
row4 3
row5 3
row6 3
row7 1
如果性能不重要或者可能使用小型DataFrame
,请使用DataFrameGroupBy.filter
:
df = df.groupby('col_id').filter(lambda x: len(x) > 2)
编辑:对于单独的DataFrame,可以通过col_id
创建DataFrames的字典:
dfs = dict(tuple(df.groupby('col_id')))
print (dfs[1])
col_id
row1 1
row2 1
row7 1
print (dfs[2])
col_id
row3 2
print (dfs[3])
col_id
row4 3
row5 3
row6 3
可能但非pythonic解决方案与全局,不建议使用(仅为了好玩):
for i, df in df.groupby('col_id'):
globals()['df{}'.format(i)] = df
print (df1)
col_id
row1 1
row2 1
row7 1
如果你想继续你的value_counts()
方法,那么按照 -
# Creating a dictionary using value_counts()
items = df.col_id.value_counts().to_dict().items()
# Filtering only those rows where duplicate entries occur more than n
n = 2
df = df[df.col_id.isin([key for key, val in items if val > n])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.