|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pandas as pd
buycount = pd.DataFrame([['苹果',9000],['香蕉',4000],['梨子',2000],['菠萝',3000]],columns=['种类','购入数量'])
data = [['苹果','2022-02-09',300],
['苹果','2022-02-25',150],
['苹果','2022-09-05',550],
['苹果','2022-09-29',154],
['苹果','2023-01-29',354],
['苹果','2023-04-19',950],
['菠萝','2022-09-29',250],
['梨子','2023-09-20',350],
['香蕉','2022-07-29',650],
['菠萝','2023-12-22',900]]
columns = ['种类','时间','卖出数量']
df1 = pd.DataFrame(data=data,columns=columns)
# print(df1)
# 将'date'列转换为日期时间类型
df1['时间'] = pd.to_datetime(df1['时间'])
# df1['时间'] = df1['时间'].dt.strftime('%Y-%m-%d')
# df1['时间'] = df1['时间'].astype(int)
# 按年份和月份分组
df1_grouped = df1.groupby([df1['时间'].dt.year, df1['时间'].dt.month]).sum()
# 打印结果
print(df1_grouped)
Traceback (most recent call last):
File "C:\Users\K\PycharmProjects\pythonProject\666.py", line 22, in <module>
df1_grouped = df1.groupby([df1['时间'].dt.year, df1['时间'].dt.month]).sum()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\groupby\groupby.py", line 2263, in sum
result = self._agg_general(
^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\groupby\groupby.py", line 1422, in _agg_general
result = self._cython_agg_general(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\groupby\groupby.py", line 1507, in _cython_agg_general
new_mgr = data.grouped_reduce(array_func)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\internals\managers.py", line 1506, in grouped_reduce
applied = blk.apply(func)
^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\internals\blocks.py", line 329, in apply
result = func(self.values, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\groupby\groupby.py", line 1490, in array_func
result = self.grouper._cython_operation(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\groupby\ops.py", line 959, in _cython_operation
return cy_op.cython_operation(
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python\Python311\Lib\site-packages\pandas\core\groupby\ops.py", line 645, in cython_operation
self._disallow_invalid_ops(dtype, is_numeric)
File "C:\Python\Python311\Lib\site-packages\pandas\core\groupby\ops.py", line 257, in _disallow_invalid_ops
raise TypeError(f"datetime64 type does not support {how} operations")
TypeError: datetime64 type does not support sum operations
代码是没有问题的,看看你的库版本对不对吧。实再不行重新安装下库,并指定下版本。
|
|