Диаграммы Spyder в коде не работают. Что такое w? - PullRequest
0 голосов
/ 07 апреля 2020

Я новичок в Spyder и работаю с данными KDD1999. Я пытаюсь создать диаграммы, основанные на наборе данных, таких как общее количество показателей srv_error. Однако, когда я пытаюсь создать эти диаграммы, появляются ошибки, и у меня есть несколько, которые я не могу решить. Я прокомментировал код. Кто-нибудь знает, что не так с кодом?

#Used to import all packanges annd/or libraries you will be useing
#pd loads and creates the data table or dataframe
import pandas as pd

####Section for loading data
#If the datafile extention has xlsx than the read_excel function should be used. If cvs than read_cvs should be used
#As this is stored in the same area the absoloute path can remain unchanged
df = pd.read_csv('kddcupdata1.csv')

#Pulls specific details
#Pulls first five rows
df.head()
#Pulls first three rows
df.head(3)

#Setting column names
df.columns = ['duration', 'protocol_type', 'service', 'flag', 'src_bytes', 'dst_bytes', 'land', 'wrong_fragment', 'urgent', 'hot', 'num_failed_logins', 'logged_in', 'lnum_compromised', 'lroot_shell', 'lsu_attempted', 'lnum_root', 'lnum_file_creations', 'lnum_shells', 'lnum_access_files', 'lnum_outbound_cmds', 'is_host_login', 'is_guest_login', 'count', 'srv_count', 'serror_rate', 'srv_serror_rate', 'rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate', 'srv_diff_host_rate', 'dst_host_count', 'dst_host_srv_count', 'dst_host_same_srv_rate', 'dst_host_diff_srv_rate', 'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate', 'dst_host_serror_rate', 'dst_host_srv_serror_rate', 'dst_host_rerror_rate', 'dst_host_srv_rerror_rate', 'label']

#Scatter graph for number of failed logins caused by srv serror rate
df.plot(kind='scatter',x='num_failed_logins',y='srv_serror_rate',color='red')


#This works
#Total num_failed_logins caused by srv_error_rate
# making a dict of list   
info = {'Attack': ['dst_host_same_srv_rate', 'dst_host_srv_rerror_rate'],   
        'Num' : [0, 1]}     
otd = pd.DataFrame(info)     
# sum of all salary stored in 'total'  
otd['total'] = otd['Num'].sum()     
print(otd)  

##################################################################################
#Charts that do not work

import matplotlib.pyplot as plt

#1 ERROR MESSAGE - AttributeError: 'list' object has no attribute 'lsu_attempted'
#Bar chart showing total 1su attempts
df['lsu_attempted'] = df['lsu_attempted'].astype(int)
df = ({'lsu_attempted':[1]})
df['lsu_attempted'].lsu_attempted(sort=0).plot.bar()
ax = df.plot.bar(x='super user attempts', y='Total of super user attempts', rot=0)
df.from_dict('all super user attempts', orient='index')
df.transpose()

#2 ERROR MESSAGE - TypeError: plot got an unexpected keyword argument 'x'
#A simple line plot
plt.plot(kind='bar',x='protocol_type',y='lsu_attempted')


#3 ERROR MESSAGE - TypeError: 'set' object is not subscriptable
df['lsu_attempted'] = df['lsu_attempted'].astype(int)
df = ({'lsu_attempted'})
df['lsu_attempted'].lsu_attempted(sort=0).plot.bar()
ax = df.plot.bar(x='protocol_type', y='lsu_attempted', rot=0)
df.from_dict('all super user attempts', orient='index')
df.transpose()

#5 ERROR MESSAGE - TypeError: 'dict' object is not callable
#Bar chart showing total of chosen protocols used
Data = {'protocol_types': ['tcp','icmp'],
        'number of protocols used': [10,20,30]
       }
bar = df(Data,columns=['protocol_types','number of protocols used'])
bar.plot(x ='protocol_types', y='number of protocols used', kind = 'bar')
df.show()

Примечание: (Также, если у кого-то есть какое-то четкое объяснение того, о чем это также может помочь, пожалуйста, по возможности, ссылки на источники?)

1 Ответ

0 голосов
/ 08 апреля 2020

Ваша первая ошибка в этом фрагменте:

df['lsu_attempted'] = df['lsu_attempted'].astype(int)
df = ({'lsu_attempted':[1]})
df['lsu_attempted'].lsu_attempted(sort=0).plot.bar()
ax = df.plot.bar(x='super user attempts', y='Total of super user attempts', rot=0)
df.from_dict('all super user attempts', orient='index')
df.transpose()

Ошибка, которую вы получаете AttributeError: 'list' object has no attribute 'lsu_attempted', является результатом второй строки выше.

Первоначально df - это pandas фрейм данных (строка 1 выше), но из строки 2 df = ({'lsu_attempted':[1]}), df теперь является словарем с одним ключом - 'lsu_attempted' - который имеет значение списка с одним элементом.

, поэтому в строке 3, когда вы do df ['lsu_attempted'] (как первая часть этого оператора) это соответствует этому списку из одного элемента, а список не имеет атрибута lsu_attempted.

Я понятия не имею, что вы пытались сделать но я уверен, что вы не намеревались заменить свой фрейм данных одним ключевым словарём.

Ваша вторая ошибка проста - вы неправильно вызываете plt.plot - x не является аргументом ключевого слова - см. matplotlib.pyplot.plot - документация Matplotlib 3.2.1 - x и y - позиционные аргументы.

Ваше третье сообщение об ошибке является результатом приведенного выше фрагмента кода - вы сделали df словарём - и ты не можешь позвонить ди ctionaries.

...