Python DataFrame Cleanup of Specific Values

Asked 2 years ago, Updated 2 years ago, 61 views

location   distance
    a          1
    a          1
    a          3
    b          1
    b          2
    b          2
    c          4
    d          1
    d          1

If there's a data frame df like this, Summarize the number of values of 2 or more for each column.

a : 1

b : 2

c : 1

d : 0

What should I do to output it like this? It's not easy to find the result I want.

python dataframe

2022-09-20 10:53

1 Answers

>>> import pandas as pd

>>> df = pd.DataFrame({"loc": list("aaabbbcdd"), "dist": [ 1,1,2,1,2,2,4,1,1 ]})
>>> df
  loc  dist
0   a     1
1   a     1
2   a     2
3   b     1
4   b     2
5   b     2
6   c     4
7   d     1
8   d     1
>>> df[df["dist"]>=2]
  loc  dist
2   a     2
4   b     2
5   b     2
6   c     4
>>> df[df["dist"]>=2].groupby("loc").count()
     dist
loc      
a       1
b       2
c       1


2022-09-20 10:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.