[英]How to count the occurrences of a string starts with a specific substring from comma separated values in a pandas data frame?
您可以執行以下操作
str.split
將每個單元格中的日期分隔到一個列表中,explode
以展平列表pd.to_datetime
轉換為日期時間並提取月份pd.crosstab
來透視/計算月份並加入。共:
s = pd.to_datetime(df['date'].str.split('\s*,\s*').explode()).dt.to_period('M')
out = pd.crosstab(s.index,s )
# this gives the expected output
df.join(out)
Output( out
):
date 2016-03 2018-06 2019-01 2019-04 2019-07
row_0
0 0 1 0 0 2
1 1 0 0 1 0
2 0 0 1 0 0
如果它們還不是日期時間對象,您可能希望首先將列(系列)轉換為日期時間: pd.to_datetime()
注意: format
參數。
然后您可以通過.dt
訪問日期時間屬性
即df[df.COLUMN_NAME.dt.month == 5]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.