teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

修正

2021/11/18 02:00

投稿

bsdfan
bsdfan

スコア4921

answer CHANGED
@@ -9,12 +9,11 @@
9
9
 
10
10
  **追記**
11
11
  DataFrameでvalue_countsが使えるのは 1.1.0以降の比較的新しめのpandasのようです。
12
- それ以前の場合は列を抜き出して、そにvalue_counts()します。
12
+ 列を抜き出して、そのSeriesにvalue_counts()すればいいです
13
13
  ```python
14
+ df_count = df['state'].value_counts().to_frame('count')
15
+ # df_count = df['state'].value_counts().sort_index().to_frame('count')
16
+
14
- # pandas 1.1以降
17
+ # pandas 1.1以降のみ
15
18
  df_count = df.value_counts('state').to_frame('count')
16
- # df.value_counts('state').sort_index().to_frame('count')
17
-
18
- # pandas 1.1より古いバージョン
19
- df_count = df['state'].value_counts().to_frame('count')
20
19
  ```

2

追記

2021/11/18 02:00

投稿

bsdfan
bsdfan

スコア4921

answer CHANGED
@@ -6,7 +6,15 @@
6
6
 
7
7
  別のやり方として、要素数を数えたいなら、そのための関数([value_counts](https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html))を使うほうが分かりやすいと思います。
8
8
  groupbyではキー名、value_countsでは出現数でソートされるという違いがあります。
9
+
10
+ **追記**
11
+ DataFrameでvalue_countsが使えるのは 1.1.0以降の比較的新しめのpandasのようです。
12
+ それ以前の場合は列を抜き出して、それにvalue_counts()します。
9
13
  ```python
14
+ # pandas 1.1以降
10
15
  df_count = df.value_counts('state').to_frame('count')
11
16
  # df.value_counts('state').sort_index().to_frame('count')
17
+
18
+ # pandas 1.1より古いバージョン
19
+ df_count = df['state'].value_counts().to_frame('count')
12
20
  ```

1

修正

2021/11/18 01:53

投稿

bsdfan
bsdfan

スコア4921

answer CHANGED
@@ -4,7 +4,6 @@
4
4
  df_count = df.groupby('state').agg(count=('state', 'count'))
5
5
  ```
6
6
 
7
-
8
7
  別のやり方として、要素数を数えたいなら、そのための関数([value_counts](https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html))を使うほうが分かりやすいと思います。
9
8
  groupbyではキー名、value_countsでは出現数でソートされるという違いがあります。
10
9
  ```python