【问题标题】:Count most repeated pair of an get that pair in pandas在熊猫中计算最重复的一对
【发布时间】:2018-10-29 05:24:50
【问题描述】:

我在一个班级项目中工作,但我不知道如何获得 DataFrame 中重复次数最多的方向(带有纬度和经度字段)。 这是我拥有的 Dataframe 的一个示例:

                                  coor      lats      longs
0           {-8.51114625, 42.90692115} -8.511146  42.906921
1            {-8.4228133, 43.34566085} -8.422813  43.345661
2           {-8.51114625, 42.90692115} -8.511146  42.906921
3            {-8.4228133, 43.34566085} -8.422813  43.345661
4           {-8.51114625, 42.90692115} -8.511146  42.906921
5           {-8.51114625, 42.90692115} -8.511146  42.906921
6           {-8.51114625, 42.90692115} -8.511146  42.906921
7           {-8.51114625, 42.90692115} -8.511146  42.906921
8           {-8.51114625, 42.90692115} -8.511146  42.906921
9           {-8.51114625, 42.90692115} -8.511146  42.906921
10           {-8.4228133, 43.34566085} -8.422813  43.345661
11           {-8.4228133, 43.34566085} -8.422813  43.345661
12          {-8.51114625, 42.90692115} -8.511146  42.906921
13          {-8.51114625, 42.90692115} -8.511146  42.906921
14           {-8.4228133, 43.34566085} -8.422813  43.345661
15           {-8.4228133, 43.34566085} -8.422813  43.345661

我执行这个:

coords.groupby(['longs','lats']).size().sort_values(ascending=False)[:5]

其中 coords 是数据文件的名称。我得到这样的东西:

longs      lats     
43.345661  -8.422813    303
42.906921  -8.511146    194
43.511210  -8.269336    120
42.798237  -8.866379     31
42.890181  -8.645030     19
dtype: int64

在这里,如果我尝试访问第一个元素,我会得到它出现的次数(在本例中我得到 303),但我需要纬度和经度:longs: 43.345661 和 lats: -8.422813。

【问题讨论】:

  • 只需将 .reset_index() 添加到代码末尾,然后重试 :)
  • @HarvIpan 你测试过你的代码吗?
  • @RafaelC,我的错。看来您的评论是要走的路。

标签: python pandas


【解决方案1】:

您可以尝试使用reset_index仅使用上面问题中显示的数据框记录):

grouped_df = coords.groupby(['longs','lats']).size().sort_values(ascending=False).to_frame('value_count').reset_index()[:5]
print(grouped_df)

分组结果:

       longs      lats  value_count
0  42.906921 -8.511146           10
1  43.345661 -8.422813            6

现在要获取第一个元素,您可以使用 .iloc:

print(grouped_df.iloc[0])

结果:

longs          42.906921
lats           -8.511146
value_count    10.000000
Name: 0, dtype: float64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2018-03-19
    • 2021-11-08
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多