python - 如何按日期排序,然后按日期添加另一列的总计

标签 python pandas csv

我如何获取一行日期并按月过滤它们,然后添加每个月的总销售额?

此代码尝试在 1 月执行此操作。

df['Release Date'] = pd.to_datetime(df['Release Date'])
print(df.loc[df['Release Date'].dt.month == 1][df['Tickets Sold'].sum())

df['Release Date'] = pd.to_datetime(df['Release Date'])
print(df.loc[df['Release Date'].dt.month == 1][df['Tickets Sold'].sum())

0 1,000 卢比纸币 ... 277 1 10 克洛弗菲尔德巷 ... 8333294 2 13小时:类加西 secret 士兵... 6110198 3 2016 年奥斯卡短裤……325643 4 20 世纪女性 ... 20644

试图将每个月售出的门票总数相加。

最佳答案

所以您要获取每个月的总数。那么您是否也尝试用这些总数做一些事情?

虚拟数据:

import pandas as pd
import numpy as np

# dummy data
date_range = pd.date_range('2019-01-01', '2019-03-31', freq='D')
df = pd.DataFrame(
    np.random.randint(1, 20, (date_range.shape[0], 1)),
    index=date_range,
    columns=['Tickets Sold'])
df['Release Date'] = df.index
df.reset_index(inplace=True, drop=True)

>>> print(df.head())
   Tickets Sold Release Date
0            15   2019-01-01
1             7   2019-01-02
2             5   2019-01-03
3             5   2019-01-04
4            19   2019-01-05

要获得总数,只需将 Release Date 列设置为 index 并在每月 M 上使用 resample > 基础。

# set column release date as index and resample.
df.set_index('Release Date', inplace=True)

>>> print(df.resample('M').sum())
              Tickets Sold
Release Date              
2019-01-31             305
2019-02-28             278
2019-03-31             322

关于python - 如何按日期排序,然后按日期添加另一列的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55930616/

相关文章:

python - 结合两个 Pandas 数据框添加相应的值

python - 向 Pandas DataFrame 添加一行会重复索引

python - 在 Django 模板中呈现列表

sql - 使用自定义文件名路径复制 csv

python - 在 Gnuplot 中设置线型?

Python 方法奇怪地暂停,直到 tkinter root 关闭

python - Python multiprocessing.Queue 线程安全吗?

python - Pandas 使用索引名称和列名称应用函数

python - TypeError : "value" parameter must be a scalar, dict 或 Series,但您在 Python 中传递了 "DataFrame"

java - 使用 JAVA 在 CSV 文件中创建列