当我想尝试p

2024-10-01 17:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我试图对U对象执行操作时,都会出错。我总是收到一个按键错误。我已经试过很多次了

import pandas as pd
users =pd.read_csv('./users.csv',sep=',',parse_dates=[30])
users.head()
users.columns.get_loc("WhenCreated")
users['Month'] = users['WhenCreated'].dt.month
users.head()
UsersCreatedin2017=users['WhenCreated'] > '2017-01-01'
users2017=users[UsersCreatedin2017].copy()
users2017[['Month','UserPrincipalName']].groupby('Month').count()
u=users2017[['Month','UserPrincipalName']].groupby('Month').count().copy()
u.plot(kind='line', x='Month', y='UserPrincipalName')

我去哪里了下面的错误

^{pr2}$

我尝试u.plot(),但得到了以下输出 在

我要绘制的数据是: 用户名PrincipalName 月份
161个 253个 344个 431个 5 34个 6月21日 7月28日 8196个 9 42


Tags: csv对象plotcount错误usersheadpd
1条回答
网友
1楼 · 发布于 2024-10-01 17:25:11

要在groupby中使用as_index=False(或在之后重置_index):

In [11]: df = pd.DataFrame([[1, 2], [1, 3], [2, 4]], columns=["A", "B"])

In [12]: df
Out[12]:
   A  B
0  1  2
1  1  3
2  2  4

In [13]: df.groupby("A").count()
Out[13]:
   B
A
1  2
2  1

In [14]: df.groupby("A", as_index=False).count()
Out[14]:
   A  B
0  1  2
1  2  1

正如您在没有As_index=False的情况下看到的,A在索引中而不是列中,这就是plot方法找不到它的原因(引发KeyError)。在

相关问题 更多 >

    热门问题