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

回答編集履歴

2

単純ミスを修正

2019/05/31 07:28

投稿

magichan
magichan

スコア15898

answer CHANGED
@@ -21,7 +21,7 @@
21
21
  import matplotlib.pyplot as plt
22
22
  matplotlib.use('TkAgg')
23
23
  df = pd.read_csv('tera1.csv', parse_dates=['日時'])
24
- df['年月'] = df['日時'].dt.strftime('%Y/%M')
24
+ df['年月'] = df['日時'].dt.strftime('%Y/%m')
25
25
  print(df)
26
26
 
27
27
  xt = pd.crosstab(index=df['年月'], columns=df['グループ'])

1

補足を追加

2019/05/31 07:28

投稿

magichan
magichan

スコア15898

answer CHANGED
@@ -1,7 +1,7 @@
1
1
  ``pandas.crosstab()``の代わりに ``df.groupby([pd.Grouper(freq='MS'), 'グループ']).count().unstack()`` を使うと月集計になるかと思います
2
2
 
3
3
  ```Python
4
- df = pd.read_csv(tera1.csv', parse_dates=['日時'], index_col='日時')
4
+ df = pd.read_csv('tera1.csv', parse_dates=['日時'], index_col='日時')
5
5
 
6
6
  #xt = pd.crosstab(df.index,df['グループ'])
7
7
 
@@ -10,4 +10,22 @@
10
10
  xt.plot(kind='bar')
11
11
 
12
12
  plt.show()
13
+ ```
14
+
15
+ ### 【追記】
16
+ 元の日時データを月毎のデータに変換したいのであれば ``Series.dt.strftime()`` にて文字列に変換するとよいかと思います。
17
+
18
+ ```Python
19
+ import pandas as pd
20
+ import matplotlib
21
+ import matplotlib.pyplot as plt
22
+ matplotlib.use('TkAgg')
23
+ df = pd.read_csv('tera1.csv', parse_dates=['日時'])
24
+ df['年月'] = df['日時'].dt.strftime('%Y/%M')
25
+ print(df)
26
+
27
+ xt = pd.crosstab(index=df['年月'], columns=df['グループ'])
28
+
29
+ xt.plot(kind='bar')
30
+ plt.show()
13
31
  ```