sourcecode

팬더는 날짜의 히스토그램을 그릴 수 있습니까?

codebag 2023. 9. 10. 12:12
반응형

팬더는 날짜의 히스토그램을 그릴 수 있습니까?

시리즈를 dtype=의 datetime 열로 강제 이동했습니다.datetime64[ns](비록 낮에만 해결하면 되겠지만...어떻게 변해야 할지 잘 모르겠습니다.

import pandas as pd
df = pd.read_csv('somefile.csv')
column = df['date']
column = pd.to_datetime(column, coerce=True)

음모는 통하지 않습니다

ipdb> column.plot(kind='hist')
*** TypeError: ufunc add cannot use operands with types dtype('<M8[ns]') and dtype('float64')

날짜 수를 주별, 월별 또는 연도별로 표시하는 히스토그램을 표시하려고 합니다.

확실히 이것을 할 수 있는 방법이 있습니다.pandas?

이 df가 주어지면:

        date
0 2001-08-10
1 2002-08-31
2 2003-08-29
3 2006-06-21
4 2002-03-27
5 2003-07-14
6 2004-06-15
7 2003-08-14
8 2003-07-29

그리고 아직 그렇지 않은 경우:

df["date"] = df["date"].astype("datetime64")

날짜 수를 월별로 표시하는 방법

df.groupby(df["date"].dt.month).count().plot(kind="bar")

.dtdatetime 속성에 액세스할 수 있습니다.

다음과 같은 결과를 얻을 수 있습니다.

groupby date month

연도별, 요일별 등 월별로 대체 가능합니다.

예를 들어 연도와 월을 구별하려면 다음 작업을 수행합니다.

df.groupby([df["date"].dt.year, df["date"].dt.month]).count().plot(kind="bar")

다음과 같은 의미가 있습니다.

groupby date month year

제 생각에는 리샘플이 당신이 찾고 있는 것일 수도 있습니다.사용자의 경우 다음을 수행합니다.

df.set_index('date', inplace=True)
# for '1M' for 1 month; '1W' for 1 week; check documentation on offset alias
df.resample('1M').count()

계산만 수행하고 플롯은 수행하지 않으므로 직접 플롯을 작성해야 합니다.

리샘플 팬더 리샘플 문서에 대한 자세한 내용은 이 게시물을 참조하십시오.

저도 당신과 비슷한 문제에 부딪혔습니다.도움이 되길 바랍니다.

이 모든 대답들은 지나치게 복잡해 보이는데, 적어도 '현대판' 팬더들에게는 두 줄로 되어 있습니다.

df.set_index('date', inplace=True)
df.resample('M').size().plot.bar()

만약 당신이 a를 가진 시리즈가 있다면,DatetimeIndex그럼 두번째 줄만 달리면 됩니다.

series.resample('M').size().plot.bar() # Just counts the rows/month
or
series.resample('M').sum().plot.bar(). # Sums up the values in the series

렌더링된 예제

enter image description here

예제 코드

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Create random datetime object."""

# core modules
from datetime import datetime
import random

# 3rd party modules
import pandas as pd
import matplotlib.pyplot as plt


def visualize(df, column_name='start_date', color='#494949', title=''):
    """
    Visualize a dataframe with a date column.

    Parameters
    ----------
    df : Pandas dataframe
    column_name : str
        Column to visualize
    color : str
    title : str
    """
    plt.figure(figsize=(20, 10))
    ax = (df[column_name].groupby(df[column_name].dt.hour)
                         .count()).plot(kind="bar", color=color)
    ax.set_facecolor('#eeeeee')
    ax.set_xlabel("hour of the day")
    ax.set_ylabel("count")
    ax.set_title(title)
    plt.show()


def create_random_datetime(from_date, to_date, rand_type='uniform'):
    """
    Create random date within timeframe.

    Parameters
    ----------
    from_date : datetime object
    to_date : datetime object
    rand_type : {'uniform'}

    Examples
    --------
    >>> random.seed(28041990)
    >>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
    datetime.datetime(1998, 12, 13, 23, 38, 0, 121628)
    >>> create_random_datetime(datetime(1990, 4, 28), datetime(2000, 12, 31))
    datetime.datetime(2000, 3, 19, 19, 24, 31, 193940)
    """
    delta = to_date - from_date
    if rand_type == 'uniform':
        rand = random.random()
    else:
        raise NotImplementedError('Unknown random mode \'{}\''
                                  .format(rand_type))
    return from_date + rand * delta


def create_df(n=1000):
    """Create a Pandas dataframe with datetime objects."""
    from_date = datetime(1990, 4, 28)
    to_date = datetime(2000, 12, 31)
    sales = [create_random_datetime(from_date, to_date) for _ in range(n)]
    df = pd.DataFrame({'start_date': sales})
    return df


if __name__ == '__main__':
    import doctest
    doctest.testmod()
    df = create_df()
    visualize(df)

다음은 여러분이 기대하는 것과 같은 히스토그램을 원하는 경우에 대한 해결책입니다.그룹 기준을 사용하지 않고 날짜 시간 값을 정수로 변환하고 그림의 레이블을 변경합니다.눈금 레이블을 짝수 위치로 이동하기 위해 약간의 개선을 수행할 수 있습니다.또한 접근 방식을 사용하면 커널 밀도 추정도(및 다른 그림)도 가능합니다.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({"datetime": pd.to_datetime(np.random.randint(1582800000000000000, 1583500000000000000, 100, dtype=np.int64))})
fig, ax = plt.subplots()
df["datetime"].astype(np.int64).plot.hist(ax=ax)
labels = ax.get_xticks().tolist()
labels = pd.to_datetime(labels)
ax.set_xticklabels(labels, rotation=90)
plt.show()

Datetime histogram

저는 (1) 데이터 프레임을 직접 사용하는 대신 매트플롯리브로 플롯을 설정하고 (2) 데이터 프레임을 사용함으로써 이 문제를 해결할 수 있었습니다.values기여하다.예제 참조:

import matplotlib.pyplot as plt

ax = plt.gca()
ax.hist(column.values)

사용하지 않으면 작동하지 않습니다.values, 왜 효과가 있는지는 모르겠지만요.

이 문제를 해결하기 위해 날짜 유형을 int 유형으로 변환하는 코드를 사용할 수 있습니다.

df['date'] = df['date'].astype(int)
df['date'] = pd.to_datetime(df['date'], unit='s')

날짜만 가져오면 다음 코드를 추가할 수 있습니다.

pd.DatetimeIndex(df.date).normalize()
df['date'] = pd.DatetimeIndex(df.date).normalize()

저도 이것 때문에 곤란을 겪고 있었습니다.당신이 날짜를 사용하고 있기 때문에 (나처럼) 시간 순서를 유지하고 싶다고 생각합니다.

그럼 해결책은.

import matplotlib.pyplot as plt    
counts = df['date'].value_counts(sort=False)
plt.bar(counts.index,counts)
plt.show()

제발, 더 좋은 방법을 아는 사람이 있다면 말해주세요.

EDIT: 위의 Jean의 경우, 다음은 데이터의 샘플입니다 [전체 데이터 집합에서 무작위로 샘플링했기 때문에 사소한 히스토그램 데이터].

print dates
type(dates),type(dates[0])
dates.hist()
plt.show()

출력:

0    2001-07-10
1    2002-05-31
2    2003-08-29
3    2006-06-21
4    2002-03-27
5    2003-07-14
6    2004-06-15
7    2002-01-17
Name: Date, dtype: object
<class 'pandas.core.series.Series'> <type 'datetime.date'>

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-f39e334eece0> in <module>()
      2 print dates
      3 print type(dates),type(dates[0])
----> 4 dates.hist()
      5 plt.show()

/anaconda/lib/python2.7/site-packages/pandas/tools/plotting.pyc in hist_series(self, by, ax, grid, xlabelsize, xrot, ylabelsize, yrot, figsize, bins, **kwds)
   2570         values = self.dropna().values
   2571 
-> 2572         ax.hist(values, bins=bins, **kwds)
   2573         ax.grid(grid)
   2574         axes = np.array([ax])

/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
   5620             for xi in x:
   5621                 if len(xi) > 0:
-> 5622                     xmin = min(xmin, xi.min())
   5623                     xmax = max(xmax, xi.max())
   5624             bin_range = (xmin, xmax)

TypeError: can't compare datetime.date to float

저는 "바"로 시계열을 짜느라 오랫동안 꼼짝 못 했습니다.예를 들어 일별 데이터와 월별 데이터와 같이 서로 다른 인덱스로 두 개의 시계열을 플롯하려고 하면 매우 이상해집니다.그런 다음 문서를 다시 읽었고, matplotlib 문서에는 막대가 범주형 데이터를 의미한다고 명시되어 있습니다.사용할 Plotting 함수는 step입니다.

더 최근의 매트플롯 리브 버전에서는 이 제한이 해제된 것으로 보입니다.이제 Axes.bar 을 사용하여 시계열을 표시할 수 있습니다.

기본 옵션을 사용하는 경우 막대는 가로 폭이 0.8일인 가로 축으로 지정된 날짜의 중앙에 배치됩니다.막대 위치는 "정렬" 매개변수로 이동할 수 있으며 너비는 스칼라 또는 가로줄 목록과 동일한 차원의 목록으로 지정할 수 있습니다.

줌 팩터에 상관없이 좋은 날짜 레이블을 사용하려면 다음 줄을 추가하기만 하면 됩니다.

plt.rcParams['date.converter'] = 'concise'

언급URL : https://stackoverflow.com/questions/27365467/can-pandas-plot-a-histogram-of-dates

반응형