我有一个地理定位社交媒体帖子的数据集,我试图通过大于 1 的 user_id
频率(发布 2 次或更多次的用户)对其进行过滤。我想对此进行过滤,以便进一步清理正在创建的轨迹数据。
示例代码:
# Import Data
data = pd.read_csv('path', delimiter=',', engine='python')
#print len(data),"rows"
#print data
# Create Data Fame
df = pd.DataFrame(data, columns=['user_id','timestamp','latitude','longitude'])
#print data.head()
# Get a list of unique user_id values
uniqueIds = np.unique(data['user_id'].values)
# Get the ordered (by timestamp) coordinates for each user_id
output = [[id,data.loc[data['user_id']==id].sort_values(by='timestamp')['latitude','longitude'].values.tolist()] for id in uniqueIds]
# Save outputs
outputs = pd.DataFrame(output)
#print outputs
outputs.to_csv('path', index=False, header=False)
我尝试使用 df[].value_counts()
获取 user_id 的计数,然后在 output = [[......data[ 'user_id']==id>1].....
但是,那没有用。是否可以将 user_id
的频率作为附加参数添加到代码中并仅提取这些用户的信息?
示例数据:
user_id, timestamp, latitude, longitude
478134225, 3/12/2017 9:04, 38.8940974, -77.0276216
478103585, 3/12/2017 9:04, 38.882584, -77.1124701
478073193, 3/12/2017 9:07, 39.00027849, -77.09480086
476194185, 3/12/2017 9:14, 38.8048355, -77.0469214
476162349, 3/12/2017 9:16, 38.8940974, -77.0276216
478073193, 3/12/2017 9:05, 38.8549, -76.8752
477899275, 3/12/2017 9:08, 38.90181532, -77.03733586
477452890, 3/12/2017 9:08, 38.96117237, -76.95561893
478073193, 3/12/2017 9:05, 38.7188716, -77.1542684
最佳答案
让我们尝试groupby
,然后是filter
方法,该方法仅返回那些在过滤函数中评估为真的记录。在这种情况下,为具有多个记录的组或 user_id 返回 True。
df.groupby('user_id').filter(lambda x: x['user_id'].count()>1)
使用转换和 bool 索引的更高效的语句。
df[df.groupby('user_id')['user_id'].transform('count') > 1]
关于python - 按列数过滤 Pandas df 并写入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43300146/