Ежедневные Упоминания Слова - PullRequest
0 голосов
/ 17 декабря 2018

У меня есть следующий df, содержащий ежедневные статьи из разных источников:

print(df)

Date         content

2018-11-01    Apple Inc. AAPL 1.54% reported its fourth cons...
2018-11-01    U.S. stocks climbed Thursday, Apple is a real ...
2018-11-02    GONE are the days when smartphone manufacturer...
2018-11-03    To historians of technology, the story of the ...
2018-11-03    Apple Inc. AAPL 1.54% reported its fourth cons...
2018-11-03    Apple is turning to traditional broadcasting t...

(...)

Я хотел бы вычислить общее количество ежедневных упоминаний - следовательно, агрегирование по дате - изслово "яблоко".Как я могу создать "final_df"?

print(final_df) 

    2018-11-01    2
    2018-11-02    0
    2018-11-03    2
    (...)

Ответы [ 3 ]

0 голосов
/ 17 декабря 2018

Используйте count для нового Series, агрегируйте по столбцу df['Date'] с sum:

df1 = df['content'].str.count('Apple').groupby(df['Date']).sum().reset_index(name='count')
print (df1)
         Date  count
0  2018-11-01      2
1  2018-11-02      0
2  2018-11-03      2
0 голосов
/ 17 декабря 2018

Вы можете попробовать альтернативное решение с str.contains с функцией groupby без использования sum все время.

>>> df
         Date                                         content
0  2018-11-01  Apple Inc. AAPL 1.54% reported its fourth cons
1  2018-11-01   U.S. stocks climbed Thursday, Apple is a real
2  2018-11-02  GONE are the days when smartphone manufacturer
3  2018-11-03   To historians of technology, the story of the
4  2018-11-03  Apple Inc. AAPL 1.54% reported its fourth cons
5  2018-11-03  Apple is turning to traditional broadcasting t

Решения:

df.content.str.contains("Apple").groupby(df['Date']).count().reset_index(name="count")

         Date  count
0  2018-11-01      2
1  2018-11-02      1
2  2018-11-03      3


# df["content"].str.contains('Apple',case=True,na=False).groupby(df['Date']).count()
0 голосов
/ 17 декабря 2018

Вы можете GroupBy различные даты, использовать str.count, чтобы подсчитать вхождения Apple и объединить с sum, чтобы получить количество подсчетов вкаждая группа:

df.groupby('Date').apply(lambda x: x.content.str.count('Apple').sum())
                  .reset_index(name='counts')

      Date     counts
0 2018-11-01       2
1 2018-11-02       0
2 2018-11-03       2
...