回答編集履歴

3

修正

2021/11/18 02:00

投稿

bsdfan
bsdfan

スコア4578

test CHANGED
@@ -20,20 +20,18 @@
20
20
 
21
21
  DataFrameでvalue_countsが使えるのは 1.1.0以降の比較的新しめのpandasのようです。
22
22
 
23
- それ以前の場合は列を抜き出して、そにvalue_counts()します。
23
+ 列を抜き出して、そのSeriesにvalue_counts()すればいいです
24
24
 
25
25
  ```python
26
26
 
27
+ df_count = df['state'].value_counts().to_frame('count')
28
+
29
+ # df_count = df['state'].value_counts().sort_index().to_frame('count')
30
+
31
+
32
+
27
- # pandas 1.1以降
33
+ # pandas 1.1以降のみ
28
34
 
29
35
  df_count = df.value_counts('state').to_frame('count')
30
36
 
31
- # df.value_counts('state').sort_index().to_frame('count')
32
-
33
-
34
-
35
- # pandas 1.1より古いバージョン
36
-
37
- df_count = df['state'].value_counts().to_frame('count')
38
-
39
37
  ```

2

追記

2021/11/18 02:00

投稿

bsdfan
bsdfan

スコア4578

test CHANGED
@@ -14,10 +14,26 @@
14
14
 
15
15
  groupbyではキー名、value_countsでは出現数でソートされるという違いがあります。
16
16
 
17
+
18
+
19
+ **追記**
20
+
21
+ DataFrameでvalue_countsが使えるのは 1.1.0以降の比較的新しめのpandasのようです。
22
+
23
+ それ以前の場合は列を抜き出して、それにvalue_counts()します。
24
+
17
25
  ```python
26
+
27
+ # pandas 1.1以降
18
28
 
19
29
  df_count = df.value_counts('state').to_frame('count')
20
30
 
21
31
  # df.value_counts('state').sort_index().to_frame('count')
22
32
 
33
+
34
+
35
+ # pandas 1.1より古いバージョン
36
+
37
+ df_count = df['state'].value_counts().to_frame('count')
38
+
23
39
  ```

1

修正

2021/11/18 01:53

投稿

bsdfan
bsdfan

スコア4578

test CHANGED
@@ -7,8 +7,6 @@
7
7
  df_count = df.groupby('state').agg(count=('state', 'count'))
8
8
 
9
9
  ```
10
-
11
-
12
10
 
13
11
 
14
12