python - 值错误 : No axis named node2 for object type <class 'pandas.core.frame.DataFrame' >

标签 python pandas dataframe

import pandas as pd
import numpy as np
from datetime import datetime

data = {'date': ['1998-03-01 00:00:01', '2001-04-01 00:00:01','1998-06-01 00:00:01','2001-08-01 00:00:01','2001-05-03 00:00:01','1994-03-01 00:00:01'], 
        'node1': [1, 1, 2,2,3,2],
     'node2': [8,316,26,35,44,56],
     'weight': [1,1,1,1,1,1], }

df2 = pd.DataFrame(data, columns = ['date', 'node1','node2','weight'])


df2['date'] = pd.to_datetime(df2['date'])

l1 = [1990,1991,1992,1993,1994,1995,1996,1997,1998]
l2 = [1999,2000,2001]
ndf = df2[df2['date'].dt.year.isin(l1+l2)]

mask = ndf.groupby('node1','node2').apply(lambda x : (x['date'].dt.year.isin(l1)).any())
mask2 = ndf.groupby('node1','node2').apply(lambda x : (x['date'].dt.year.isin(l2)).any())

我得到的错误-

Traceback (most recent call last):
  File "datanew.py", line 32, in <module>
    mask = ndf.groupby('node1','node2').apply(lambda x : (x['date'].dt.year.isin(l1)).any())
  File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 5159, in groupby
    axis = self._get_axis_number(axis)
  File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 357, in _get_axis_number
    .format(axis, type(self)))
ValueError: No axis named node2 for object type <class 'pandas.core.frame.DataFrame'>

我已经在数据中定义了“node2”列,但错误仍然是说 node2 没有轴。似乎是什么问题?

最佳答案

groupby 中需要 []:

.groupby(['node1','node2'])

mask = ndf.groupby(['node1','node2']).apply(lambda x : (x['date'].dt.year.isin(l1)).any())
print (mask)
node1  node2
1      8         True
       316      False
2      26        True
       35       False
       56        True
3      44       False
dtype: bool

mask2 = ndf.groupby(['node1','node2']).apply(lambda x : (x['date'].dt.year.isin(l2)).any())
print (mask2)
node1  node2
1      8        False
       316       True
2      26       False
       35        True
       56       False
3      44        True
dtype: bool

关于python - 值错误 : No axis named node2 for object type <class 'pandas.core.frame.DataFrame' >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754388/

相关文章:

python - 当小部件失去焦点时如何拦截

python - 当我更改 DataFrame 的索引时,使用 pandas 进行绘图似乎效果不佳

python - 如何从列中拆分字符串以创建长格式数据框

Python - 将列值分组到类中

R:在数据框中插入多行(变量数)

python - 大矩阵对角化python

python - 什么时候在 Django 中使用 "AbstractBaseUser"?

python - telegram-cli中有 "terminate all other sessions"的命令吗?

python - 如果 Pandas 数据框中的特定列中存在空值,则删除行

python - 在 pandas 数据框中查找频繁用户