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

时间:2019-06-12 08:19:11

标签: 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

如何根据value_counts()advertisement_id绘制这两列以查看day的{​​{1}}?

我有以下代码:

month

如何对月份进行分组并绘制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()

1 个答案:

答案 0 :(得分:0)

您真的很亲密!

connect_start列转换为日期时间后,您可以像这样提取monthday

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值。我把它放在左下角。

希望有帮助!