python - 如何绘制非数值数据的日期时间和 value_counts() ?

标签 python matplotlib plotly-dash

我有以下列connect_start

0   2019-01-01 00:01:44
1   2019-01-01 00:02:57
2   2019-01-01 00:24:09
3   2019-01-01 01:35:23
4   2019-01-01 01:46:41

以及客户观看以访问互联网的一列 advertisement_id 示例:

0 1
1 2 
2 3
3 2
4 1

如何绘制这两列以根据月查看advertisement_idvalue_counts()?

我有以下代码:

df = pd.read_csv('./input/data.csv', sep=';')
df['connect_start'] = pd.to_datetime(df['connect_start'], format='%Y/%m/%d %H:%M:%S')

如何对月份进行分组并绘制advertisement_id.value()

这是我的尝试,我的计算机多次崩溃。任何人都可以帮忙。

df['connect_start'] = pd.to_datetime(df['connect_start'], format='%Y/%m/%d %H:%M:%S')

df.groupby('connect_start)['advertisement_id']

最佳答案

你真的很接近!

connect_start 列转换为日期时间后,您可以提取 ,如下所示:

df["my_date_column"].dt.day

然后,您可以像之前所做的那样使用 groupby 对数据进行分组

然后,您可以通过调用 sum 方法对每个组进行求和(doc) .

最后,您可以从DataFrame.plot.bar绘制它。 (doc)

这是一个工作示例:

# import modules
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(2019)

##############################################
# Just for example: create a random dataset  #
##############################################

number_row = 10


def random_dates(start, end, n):
    """  Generate n random dates between the interval """
    start_u = pd.to_datetime(start).value//10**9
    end_u = pd.to_datetime(end).value//10**9
    return pd.to_datetime(np.random.randint(start_u, end_u, n), unit='s')

# create the dataframe
df = pd.DataFrame({"connect_start": random_dates("2019-01-01", "2019-12-31", number_row),
                   "advertisement_id": np.random.randint(0, 10, number_row)})

print(df)
#         connect_start  advertisement_id
# 0 2019-09-08 18: 34: 48                 0
# 1 2019-11-05 06: 30: 10                 0
# 2 2019-05-03 01: 32: 15                 7
# 3 2019-01-13 06: 37: 25                 8
# 4 2019-12-04 03: 47: 36                 5
# 5 2019-11-23 14: 12: 14                 3
# 6 2019-09-09 18: 39: 50                 0
# 7 2019-10-01 08: 38: 53                 2
# 8 2019-04-05 21: 37: 19                 5
# 9 2019-04-25 04: 26: 52                 7

##############################################
#                   Process                  #
##############################################

# Convert connect_start as datetime type
df["connect_start"] = pd.to_datetime(df.connect_start, format="%Y-%m-%d %H:%M:%S")

# Extract day of month, date, month in 3 new columns
df["day_in_month"] = df["connect_start"].dt.day
df["day_per_year"] = df['connect_start'].dt.date
df["month"] = df["connect_start"].dt.month

print(df)
#           connect_start  advertisement_id  day_in_month day_per_year  month
# 0 2019-09-08 18: 34: 48                 0             8   2019-09-08      9
# 1 2019-11-05 06: 30: 10                 0             5   2019-11-05     11
# 2 2019-05-03 01: 32: 15                 7             3   2019-05-03      5
# 3 2019-01-13 06: 37: 25                 8            13   2019-01-13      1
# 4 2019-12-04 03: 47: 36                 5             4   2019-12-04     12
# 5 2019-11-23 14: 12: 14                 3            23   2019-11-23     11
# 6 2019-09-09 18: 39: 50                 0             9   2019-09-09      9
# 7 2019-10-01 08: 38: 53                 2             1   2019-10-01     10
# 8 2019-04-05 21: 37: 19                 5             5   2019-04-05      4
# 9 2019-04-25 04: 26: 52                 7            25   2019-04-25      4


# Compute the number advertisement_id per group
df_day_in_month = df[["advertisement_id", "day_in_month"]].groupby(by="day_in_month").sum()
df_day_per_year = df[["advertisement_id", "day_per_year"]].groupby(by="day_per_year").sum()
df_month = df[["advertisement_id", "month"]].groupby(by="month").sum()

# Fulfill with 0 for all days off the month
df_day_in_month_all_days = df_day_in_month.reindex(np.arange(1, 32), fill_value=0)


#####################################
#               Diplay              #
#####################################
# Create figure
fig, axes = plt.subplots(nrows=2, ncols=2)

# Define subplots
df_day_in_month.plot.bar(ax=axes[0, 0], rot=0)
df_day_per_year.plot.bar(ax=axes[0, 1], rot=45)
df_day_in_month_all_days.plot.bar(ax=axes[1, 0], rot=0)
df_month.plot.bar(ax=axes[1, 1], rot=0)

# Prevent plot overlapping
plt.tight_layout()
plt.show()

输出: enter image description here

如果您有一些周期不完整的事项(取决于数据集的大小),您可以在没有值的地方人为添加0值。我为左下图编辑了它。

希望有帮助!

关于python - 如何绘制非数值数据的日期时间和 value_counts() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56557617/

相关文章:

python - move/重写与具有多个txt文件的文件夹中的字符串匹配的txt文件

python - 如何在 Kivy-iOS 上修改屏幕分辨率

python - 科学刻度标签符号调整

python - 如何在matplotlib中绘制三次样条

python - 类型错误 : unhashable type: 'numpy.ndarray' in plt. 分散

python - 如何在 Dash/Plotly 应用程序中自动为多个图形添加回调

python - Dash回调 'unexpected EOF while parsing'错误

python - 处理 sklearn.tree.DecisionTreeClassifier 中的连续变量

python - 我可以在 gevent 应用程序的 strace 输出中 grep 什么来测试它是否正在使用阻塞网络 IO?

python - 无法在破折号应用程序中加载静态 css 文件