簡體   English   中英

如何從 pandas 數據幀中的逗號分隔值計算以特定 substring 開頭的字符串的出現次數?

[英]How to count the occurrences of a string starts with a specific substring from comma separated values in a pandas data frame?

我是 Python 的新手。 我正在使用看起來像這樣的 dataframe(360000 行和 2 列):business_id date

P01         2019-07-6 , 2018-06-05, 2019-07-06...
P02         2016-03-6 , 2019-04-10
P03         2019-01-02

日期列包含用逗號分隔的日期和 2010-2019 年的日期。 我試圖僅計算每個企業 ID 的 2019 年每個月的日期。 具體來說,我正在尋找 output:

在此處輸入圖像描述

誰能幫幫我嗎? 謝謝。

您可以執行以下操作

  1. 首先使用str.split將每個單元格中的日期分隔到一個列表中,
  2. 然后explode以展平列表
  3. 使用pd.to_datetime轉換為日期時間並提取月份
  4. 最后使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM