path
stringlengths 13
17
| screenshot_names
sequencelengths 1
873
| code
stringlengths 0
40.4k
| cell_type
stringclasses 1
value |
---|---|---|---|
72085616/cell_53 | [
"text_plain_output_1.png"
] | X_valid_full.shape
X_valid_full.columns | code |
72085616/cell_10 | [
"text_plain_output_1.png"
] | import pandas as pd
import pandas as pd
from sklearn.model_selection import train_test_split
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
data.shape
y = data.Price
y.isnull().count()
melb_predictors = data.drop(['Price'], axis=1)
melb_predictors.shape
melb_predictors.dtypes
X = melb_predictors.select_dtypes(exclude=['object'])
X.shape
X.dtypes | code |
72085616/cell_71 | [
"text_plain_output_1.png"
] | from sklearn.impute import SimpleImputer
import pandas as pd
import pandas as pd
from sklearn.model_selection import train_test_split
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
data.shape
pd.set_option('display.max_columns', None)
cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()]
cols_with_missing
test_cols_with_missing = []
for col in X_train.columns:
if X_train[col].isnull().any():
test_cols_with_missing.append(col)
test_cols_with_missing
reduced_X_train = X_train.drop(cols_with_missing, axis=1)
reduced_X_valid = X_valid.drop(cols_with_missing, axis=1)
from sklearn.impute import SimpleImputer
my_imputer = SimpleImputer()
imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train))
imputed_X_valid = pd.DataFrame(my_imputer.transform(X_valid))
imputed_X_train.columns = X_train.columns
imputed_X_valid.columns = X_valid.columns
X_train_plus = X_train.copy()
X_valid_plus = X_valid.copy()
X_train_full.shape
X_valid_full.shape
X_valid_full.columns
cols_with_missing = [col for col in X_train_full.columns if X_train_full[col].isnull().any()]
cols_with_missing
X_train_full.drop(cols_with_missing, axis=1, inplace=True)
X_valid_full.drop(cols_with_missing, axis=1, inplace=True)
low_cardinality_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() < 10 and X_train_full[cname].dtype == 'object']
low_cardinality_cols
numerical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].dtype in ['int64', 'float64']]
numerical_cols
my_cols = low_cardinality_cols + numerical_cols
X_train = X_train_full[my_cols].copy()
X_valid = X_valid_full[my_cols].copy()
X_train.shape
cat_variables = X_train.dtypes == 'object'
type(cat_variables)
drop_X_train = X_train.select_dtypes(exclude=['object'])
drop_X_valid = X_valid.select_dtypes(exclude=['object'])
drop_X_train.shape | code |
72085616/cell_5 | [
"text_plain_output_1.png"
] | import pandas as pd
import pandas as pd
from sklearn.model_selection import train_test_split
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
data.shape
y = data.Price
y.isnull().count() | code |
72085616/cell_36 | [
"text_html_output_1.png"
] | from sklearn.impute import SimpleImputer
import pandas as pd
import pandas as pd
from sklearn.model_selection import train_test_split
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
data.shape
pd.set_option('display.max_columns', None)
cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()]
cols_with_missing
test_cols_with_missing = []
for col in X_train.columns:
if X_train[col].isnull().any():
test_cols_with_missing.append(col)
test_cols_with_missing
reduced_X_train = X_train.drop(cols_with_missing, axis=1)
reduced_X_valid = X_valid.drop(cols_with_missing, axis=1)
from sklearn.impute import SimpleImputer
my_imputer = SimpleImputer()
imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train))
imputed_X_valid = pd.DataFrame(my_imputer.transform(X_valid))
imputed_X_train.columns = X_train.columns
imputed_X_valid.columns = X_valid.columns
X_train_plus = X_train.copy()
X_valid_plus = X_valid.copy()
X_valid_plus | code |
322985/cell_4 | [
"text_plain_output_1.png"
] | import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.linear_model as sk
full_data_set = pd.read_csv('../input/nflplaybyplay2015.csv', low_memory=False)
Pass_Plays = full_data_set.loc[full_data_set.PlayType == 'Pass']
Sack_Plays = full_data_set.loc[full_data_set.PlayType == 'Sack']
P_S_data = pd.concat([Pass_Plays, Sack_Plays])
good_columns = ['Drive', 'qtr', 'down', 'TimeUnder', 'TimeSecs', 'PlayTimeDiff', 'yrdline100', 'ydstogo']
good_columns += ['ScoreDiff', 'PosTeamScore', 'DefTeamScore']
good_columns += ['Sack']
uncleaned_data = P_S_data[good_columns]
uncleaned_data.qtr.unique() | code |
322985/cell_3 | [
"text_html_output_1.png"
] | import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.linear_model as sk
full_data_set = pd.read_csv('../input/nflplaybyplay2015.csv', low_memory=False)
Pass_Plays = full_data_set.loc[full_data_set.PlayType == 'Pass']
Sack_Plays = full_data_set.loc[full_data_set.PlayType == 'Sack']
P_S_data = pd.concat([Pass_Plays, Sack_Plays])
good_columns = ['Drive', 'qtr', 'down', 'TimeUnder', 'TimeSecs', 'PlayTimeDiff', 'yrdline100', 'ydstogo']
good_columns += ['ScoreDiff', 'PosTeamScore', 'DefTeamScore']
good_columns += ['Sack']
uncleaned_data = P_S_data[good_columns]
uncleaned_data.head() | code |
322985/cell_5 | [
"text_html_output_1.png",
"application_vnd.jupyter.stderr_output_1.png"
] | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.linear_model as sk
full_data_set = pd.read_csv('../input/nflplaybyplay2015.csv', low_memory=False)
Pass_Plays = full_data_set.loc[full_data_set.PlayType == 'Pass']
Sack_Plays = full_data_set.loc[full_data_set.PlayType == 'Sack']
P_S_data = pd.concat([Pass_Plays, Sack_Plays])
good_columns = ['Drive', 'qtr', 'down', 'TimeUnder', 'TimeSecs', 'PlayTimeDiff', 'yrdline100', 'ydstogo']
good_columns += ['ScoreDiff', 'PosTeamScore', 'DefTeamScore']
good_columns += ['Sack']
uncleaned_data = P_S_data[good_columns]
uncleaned_data.qtr.unique()
def quarter_binary(df, name, number):
df[name] = np.where(df['qtr'] == number, 1, 0)
return df
for x in [['qt1', 1], ['qt2', 2], ['qt3', 3], ['qt4', 4], ['qt5', 5]]:
uncleaned_data = quarter_binary(uncleaned_data, x[0], x[1])
del uncleaned_data['qtr']
uncleaned_data.head() | code |
331783/cell_9 | [
"text_html_output_1.png"
] | import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
df_countries = pd.read_csv('../input/Country.csv')
df_indicators = pd.read_csv('../input/Indicators.csv')
df_series = pd.read_csv('../input/Series.csv')
df_indicators[df_indicators.CountryName == 'Indonesia'].drop_duplicates('IndicatorCode')['IndicatorName'].iloc[1]
df_indo = df_indicators[df_indicators.CountryName == 'Indonesia']
len(df_indicators[df_indicators.CountryName == 'Indonesia'])
df_countries = pd.read_csv('../input/Country.csv')
df_indicators = pd.read_csv('../input/Indicators.csv')
df_series = pd.read_csv('../input/Series.csv')
df_indicators[df_indicators.CountryName == 'Indonesia'].drop_duplicates('IndicatorCode') | code |
331783/cell_4 | [
"text_plain_output_1.png",
"image_output_1.png"
] | import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
df_countries = pd.read_csv('../input/Country.csv')
df_indicators = pd.read_csv('../input/Indicators.csv')
df_series = pd.read_csv('../input/Series.csv')
df_indicators[df_indicators.CountryName == 'Indonesia'].drop_duplicates('IndicatorCode')['IndicatorName'].iloc[1] | code |
331783/cell_6 | [
"text_plain_output_1.png"
] | import matplotlib.pyplot as plt
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
df_countries = pd.read_csv('../input/Country.csv')
df_indicators = pd.read_csv('../input/Indicators.csv')
df_series = pd.read_csv('../input/Series.csv')
df_indicators[df_indicators.CountryName == 'Indonesia'].drop_duplicates('IndicatorCode')['IndicatorName'].iloc[1]
df_indo = df_indicators[df_indicators.CountryName == 'Indonesia']
ind_code = 'SP.ADO.TFRT'
data = df_indo[df_indo.IndicatorCode == ind_code]
plt.grid()
plt.ylabel('Value')
plt.xlabel('Year')
line1, = plt.plot(data['Year'], data['Value'], label=data['IndicatorCode'])
plt.legend([line1]) | code |
331783/cell_2 | [
"text_plain_output_1.png"
] | from subprocess import check_output
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from subprocess import check_output
print(check_output(['ls', '../input']).decode('utf8')) | code |
331783/cell_7 | [
"text_html_output_1.png"
] | import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
df_countries = pd.read_csv('../input/Country.csv')
df_indicators = pd.read_csv('../input/Indicators.csv')
df_series = pd.read_csv('../input/Series.csv')
df_indicators[df_indicators.CountryName == 'Indonesia'].drop_duplicates('IndicatorCode')['IndicatorName'].iloc[1]
df_indo = df_indicators[df_indicators.CountryName == 'Indonesia']
len(df_indicators[df_indicators.CountryName == 'Indonesia']) | code |
331783/cell_10 | [
"text_plain_output_1.png"
] | import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
df_countries = pd.read_csv('../input/Country.csv')
df_indicators = pd.read_csv('../input/Indicators.csv')
df_series = pd.read_csv('../input/Series.csv')
df_countries = pd.read_csv('../input/Country.csv')
df_indicators = pd.read_csv('../input/Indicators.csv')
df_series = pd.read_csv('../input/Series.csv')
df_countries[df_countries.CountryCode == 'IDN'] | code |
129018594/cell_9 | [
"text_plain_output_1.png"
] | from datasets import load_dataset
from sentence_transformers import InputExample
from sentence_transformers.cross_encoder import CrossEncoder
from sentence_transformers.cross_encoder.evaluation import CECorrelationEvaluator
from torch.utils.data import DataLoader
dataset_train = load_dataset('stsb_multi_mt', name='it', split='train')
dataset_test = load_dataset('stsb_multi_mt', name='it', split='test')
gold_samples = []
batch_size = 16
for df in dataset_train:
score = float(df['similarity_score']) / 5.0
gold_samples.append(InputExample(texts=[df['sentence1'], df['sentence2']], label=score))
gold_samples.append(InputExample(texts=[df['sentence2'], df['sentence1']], label=score))
train_dataloader = DataLoader(gold_samples, shuffle=True, batch_size=batch_size)
from sentence_transformers.cross_encoder import CrossEncoder
model_checkpoint = 'dbmdz/bert-base-italian-uncased'
cross_encoder = CrossEncoder(model_checkpoint, num_labels=1)
from sentence_transformers.cross_encoder.evaluation import CECorrelationEvaluator
import math
evaluator = CECorrelationEvaluator([[x['sentence1'], x['sentence2']] for x in dataset_test], [x / 5.0 for x in dataset_test['similarity_score']])
num_epochs = 4
evaluation_steps = 500
warmup_steps = int(len(train_dataloader) * num_epochs * 0.1)
cross_encoder.fit(train_dataloader=train_dataloader, evaluator=evaluator, epochs=num_epochs, evaluation_steps=evaluation_steps, warmup_steps=warmup_steps, save_best_model=True, output_path='cross-encoder/') | code |
129018594/cell_4 | [
"application_vnd.jupyter.stderr_output_1.png"
] | from datasets import load_dataset
dataset_train = load_dataset('stsb_multi_mt', name='it', split='train')
dataset_test = load_dataset('stsb_multi_mt', name='it', split='test') | code |
129018594/cell_2 | [
"text_plain_output_2.png",
"text_plain_output_1.png"
] | !pip install datasets | code |
129018594/cell_1 | [
"text_plain_output_1.png"
] | !pip install -U sentence-transformers | code |
129018594/cell_10 | [
"text_plain_output_1.png"
] | from datasets import load_dataset
from sentence_transformers import InputExample
from sentence_transformers.cross_encoder import CrossEncoder
from sentence_transformers.cross_encoder.evaluation import CECorrelationEvaluator
from torch.utils.data import DataLoader
dataset_train = load_dataset('stsb_multi_mt', name='it', split='train')
dataset_test = load_dataset('stsb_multi_mt', name='it', split='test')
gold_samples = []
batch_size = 16
for df in dataset_train:
score = float(df['similarity_score']) / 5.0
gold_samples.append(InputExample(texts=[df['sentence1'], df['sentence2']], label=score))
gold_samples.append(InputExample(texts=[df['sentence2'], df['sentence1']], label=score))
train_dataloader = DataLoader(gold_samples, shuffle=True, batch_size=batch_size)
from sentence_transformers.cross_encoder import CrossEncoder
model_checkpoint = 'dbmdz/bert-base-italian-uncased'
cross_encoder = CrossEncoder(model_checkpoint, num_labels=1)
from sentence_transformers.cross_encoder.evaluation import CECorrelationEvaluator
import math
evaluator = CECorrelationEvaluator([[x['sentence1'], x['sentence2']] for x in dataset_test], [x / 5.0 for x in dataset_test['similarity_score']])
num_epochs = 4
evaluation_steps = 500
warmup_steps = int(len(train_dataloader) * num_epochs * 0.1)
cross_encoder.fit(train_dataloader=train_dataloader, evaluator=evaluator, epochs=num_epochs, evaluation_steps=evaluation_steps, warmup_steps=warmup_steps, save_best_model=True, output_path='cross-encoder/')
evaluator(cross_encoder) | code |
18159419/cell_13 | [
"text_html_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
data.head() | code |
18159419/cell_9 | [
"text_plain_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
data.head() | code |
18159419/cell_4 | [
"text_plain_output_2.png",
"text_plain_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
data.head() | code |
18159419/cell_34 | [
"text_plain_output_1.png"
] | from sklearn.metrics import accuracy_score
from sklearn.metrics import accuracy_score
(train_df.shape, val_df.shape)
accuracy_score(train_df['Reg_clicks_categorical'], train_df['prediction']) | code |
18159419/cell_23 | [
"text_plain_output_1.png"
] | from keras.preprocessing.text import Tokenizer
import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
(train_df.shape, val_df.shape)
embed_size = 100
max_features = 100000
maxlen = 1400
train_X = train_df['entire_text'].fillna('##').values
val_X = val_df['entire_text'].fillna('##').values
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(data['entire_text'].fillna('##').values))
train_X = tokenizer.texts_to_sequences(train_X)
val_X = tokenizer.texts_to_sequences(val_X)
print('after tokenization')
print(len(train_X))
print(len(val_X)) | code |
18159419/cell_30 | [
"text_plain_output_1.png"
] | from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import LSTM
from keras.models import Sequential
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
(train_df.shape, val_df.shape)
embed_size = 100
max_features = 100000
maxlen = 1400
train_X = train_df['entire_text'].fillna('##').values
val_X = val_df['entire_text'].fillna('##').values
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(data['entire_text'].fillna('##').values))
train_X = tokenizer.texts_to_sequences(train_X)
val_X = tokenizer.texts_to_sequences(val_X)
train_X = pad_sequences(train_X, maxlen=maxlen)
val_X = pad_sequences(val_X, maxlen=maxlen)
train_y = train_df['Reg_clicks_categorical'].values
val_y = val_df['Reg_clicks_categorical'].values
train_y = to_categorical(train_y, num_classes=4)
val_y = to_categorical(val_y, num_classes=4)
model = Sequential()
model.add(Embedding(max_features, embed_size, input_length=maxlen))
model.add(LSTM(256))
model.add(Dense(4, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(train_X, train_y, epochs=2, batch_size=256, validation_data=(val_X, val_y))
y_prediction = model.predict(train_X, batch_size=512, verbose=1) | code |
18159419/cell_33 | [
"text_plain_output_1.png"
] | from sklearn.metrics import confusion_matrix
from sklearn.metrics import confusion_matrix
(train_df.shape, val_df.shape)
confusion_matrix(train_df['Reg_clicks_categorical'], train_df['prediction']) | code |
18159419/cell_20 | [
"text_plain_output_1.png"
] | (train_df.shape, val_df.shape) | code |
18159419/cell_6 | [
"text_plain_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
data.head() | code |
18159419/cell_29 | [
"text_plain_output_1.png"
] | from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import LSTM
from keras.models import Sequential
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
(train_df.shape, val_df.shape)
embed_size = 100
max_features = 100000
maxlen = 1400
train_X = train_df['entire_text'].fillna('##').values
val_X = val_df['entire_text'].fillna('##').values
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(data['entire_text'].fillna('##').values))
train_X = tokenizer.texts_to_sequences(train_X)
val_X = tokenizer.texts_to_sequences(val_X)
train_X = pad_sequences(train_X, maxlen=maxlen)
val_X = pad_sequences(val_X, maxlen=maxlen)
train_y = train_df['Reg_clicks_categorical'].values
val_y = val_df['Reg_clicks_categorical'].values
train_y = to_categorical(train_y, num_classes=4)
val_y = to_categorical(val_y, num_classes=4)
model = Sequential()
model.add(Embedding(max_features, embed_size, input_length=maxlen))
model.add(LSTM(256))
model.add(Dense(4, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(train_X, train_y, epochs=2, batch_size=256, validation_data=(val_X, val_y)) | code |
18159419/cell_11 | [
"text_html_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
data.head() | code |
18159419/cell_1 | [
"application_vnd.jupyter.stderr_output_1.png"
] | import warnings
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from textblob import TextBlob
import nltk
import re
from bs4 import BeautifulSoup
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from scipy.sparse import coo_matrix, hstack
import warnings
warnings.filterwarnings('ignore')
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from keras.models import Sequential
from keras.layers import LSTM
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import Bidirectional, GlobalMaxPool1D, Flatten
from keras.optimizers import Adam
from keras.models import Model
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints, optimizers, layers
from nltk.corpus import stopwords
from keras.utils import to_categorical | code |
18159419/cell_7 | [
"text_plain_output_1.png"
] | import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
plt.figure(figsize=(6, 4))
ax = sns.countplot(x='country_desc', data=data)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha='right')
plt.tight_layout()
plt.show() | code |
18159419/cell_18 | [
"text_html_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
data['Reg_clicks_categorical'].value_counts() | code |
18159419/cell_15 | [
"text_html_output_1.png"
] | import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
plt.figure(figsize=(6,4))
ax = sns.countplot(x="country_desc", data=data)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.tight_layout()
plt.show()
plt.hist(data['length_of_text'], bins=1000) | code |
18159419/cell_16 | [
"text_html_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
data['knt'].describe() | code |
18159419/cell_14 | [
"image_output_1.png"
] | import pandas as pd
data = pd.read_csv('../input/mondaq_data_adeel.csv', header=None)
columns = ['article_id', 'knt', 'unknt', 'her_knt', 'unher_knt', 'company_id', 'company_name', 'country_id', 'country_desc', 'primary_topic_id', 'topic_desc', 'article_start_date', 'daysold', 'topics', 'coauthors', 'linkedinphoto', 'title', 'body']
data.columns = columns
data['length_of_text'].describe() | code |
18159419/cell_22 | [
"image_output_1.png"
] | (train_df.shape, val_df.shape)
train_X = train_df['entire_text'].fillna('##').values
val_X = val_df['entire_text'].fillna('##').values
print('before tokenization')
print(train_X.shape)
print(val_X.shape) | code |
18159419/cell_27 | [
"text_plain_output_1.png"
] | from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import LSTM
from keras.models import Sequential
embed_size = 100
max_features = 100000
maxlen = 1400
model = Sequential()
model.add(Embedding(max_features, embed_size, input_length=maxlen))
model.add(LSTM(256))
model.add(Dense(4, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary()) | code |
17132918/cell_13 | [
"image_output_1.png"
] | import matplotlib.pyplot as plt
import random
import random
import matplotlib
import matplotlib.pyplot as plt
def throw():
global x
x += random.randint(1, 6)
def multi_throw(dice_amount, list_name):
global x
x = 0
for i in range(dice_amount):
throw()
list_name.append(x)
def multi_times(time_amount, dice_amount, list_name):
for i in range(time_amount):
multi_throw(dice_amount, list_name)
x = 0
th_amount = 1000000
my_list1 = []
my_list2 = []
my_list3 = []
my_list4 = []
multi_times(th_amount, 3, my_list1)
multi_times(th_amount, 4, my_list2)
multi_times(th_amount, 5, my_list3)
multi_times(th_amount, 6, my_list4)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list3,
bins=range(0,36),
color="blue",
alpha=0.8,
)
plt.show()
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list4,
bins=range(0,36),
color="red",
alpha=0.8,
)
plt.show()
list_100 = []
multi_times(th_amount, 100, list_100)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(list_100,
color="green",
bins=range(275,425),
alpha=0.8,
)
plt.show()
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of ' + str(th_amount) + ' dice throws')
histy = 'step'
ax.hist(my_list4, bins=range(2, 36), color='red', alpha=1.0)
ax.hist(my_list3, bins=range(2, 36), color='blue', alpha=0.8)
ax.hist(my_list2, bins=range(2, 36), color='green', alpha=0.7)
ax.hist(my_list1, bins=range(2, 36), color='yellow', alpha=0.5)
ax.legend(['6 dices', '5 dices', '4 dices', '3 dices'])
plt.show() | code |
17132918/cell_9 | [
"text_plain_output_1.png",
"image_output_1.png"
] | import matplotlib.pyplot as plt
import random
import random
import matplotlib
import matplotlib.pyplot as plt
def throw():
global x
x += random.randint(1, 6)
def multi_throw(dice_amount, list_name):
global x
x = 0
for i in range(dice_amount):
throw()
list_name.append(x)
def multi_times(time_amount, dice_amount, list_name):
for i in range(time_amount):
multi_throw(dice_amount, list_name)
x = 0
th_amount = 1000000
my_list1 = []
my_list2 = []
my_list3 = []
my_list4 = []
multi_times(th_amount, 3, my_list1)
multi_times(th_amount, 4, my_list2)
multi_times(th_amount, 5, my_list3)
multi_times(th_amount, 6, my_list4)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list3,
bins=range(0,36),
color="blue",
alpha=0.8,
)
plt.show()
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of ' + str(th_amount) + ' dice throws')
histy = 'step'
ax.hist(my_list4, bins=range(0, 36), color='red', alpha=0.8)
plt.show() | code |
17132918/cell_7 | [
"text_plain_output_1.png",
"image_output_1.png"
] | import matplotlib.pyplot as plt
import random
import random
import matplotlib
import matplotlib.pyplot as plt
def throw():
global x
x += random.randint(1, 6)
def multi_throw(dice_amount, list_name):
global x
x = 0
for i in range(dice_amount):
throw()
list_name.append(x)
def multi_times(time_amount, dice_amount, list_name):
for i in range(time_amount):
multi_throw(dice_amount, list_name)
x = 0
th_amount = 1000000
my_list1 = []
my_list2 = []
my_list3 = []
my_list4 = []
multi_times(th_amount, 3, my_list1)
multi_times(th_amount, 4, my_list2)
multi_times(th_amount, 5, my_list3)
multi_times(th_amount, 6, my_list4)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of ' + str(th_amount) + ' dice throws')
histy = 'step'
ax.hist(my_list3, bins=range(0, 36), color='blue', alpha=0.8)
plt.show() | code |
17132918/cell_15 | [
"image_output_1.png"
] | import random
import seaborn as sns
import random
import matplotlib
import matplotlib.pyplot as plt
def throw():
global x
x += random.randint(1, 6)
def multi_throw(dice_amount, list_name):
global x
x = 0
for i in range(dice_amount):
throw()
list_name.append(x)
def multi_times(time_amount, dice_amount, list_name):
for i in range(time_amount):
multi_throw(dice_amount, list_name)
x = 0
th_amount = 1000000
my_list1 = []
my_list2 = []
my_list3 = []
my_list4 = []
multi_times(th_amount, 3, my_list1)
multi_times(th_amount, 4, my_list2)
multi_times(th_amount, 5, my_list3)
multi_times(th_amount, 6, my_list4)
import seaborn as sns
sns.distplot(my_list1, kde=False) | code |
17132918/cell_16 | [
"image_output_1.png"
] | import random
import seaborn as sns
import random
import matplotlib
import matplotlib.pyplot as plt
def throw():
global x
x += random.randint(1, 6)
def multi_throw(dice_amount, list_name):
global x
x = 0
for i in range(dice_amount):
throw()
list_name.append(x)
def multi_times(time_amount, dice_amount, list_name):
for i in range(time_amount):
multi_throw(dice_amount, list_name)
x = 0
th_amount = 1000000
my_list1 = []
my_list2 = []
my_list3 = []
my_list4 = []
multi_times(th_amount, 3, my_list1)
multi_times(th_amount, 4, my_list2)
multi_times(th_amount, 5, my_list3)
multi_times(th_amount, 6, my_list4)
import seaborn as sns
sns.distplot(my_list1, kde=False)
sns.distplot(my_list2, kde=False) | code |
17132918/cell_17 | [
"text_plain_output_1.png",
"image_output_1.png"
] | import matplotlib.pyplot as plt
import random
import seaborn as sns
import random
import matplotlib
import matplotlib.pyplot as plt
def throw():
global x
x += random.randint(1, 6)
def multi_throw(dice_amount, list_name):
global x
x = 0
for i in range(dice_amount):
throw()
list_name.append(x)
def multi_times(time_amount, dice_amount, list_name):
for i in range(time_amount):
multi_throw(dice_amount, list_name)
x = 0
th_amount = 1000000
my_list1 = []
my_list2 = []
my_list3 = []
my_list4 = []
multi_times(th_amount, 3, my_list1)
multi_times(th_amount, 4, my_list2)
multi_times(th_amount, 5, my_list3)
multi_times(th_amount, 6, my_list4)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list3,
bins=range(0,36),
color="blue",
alpha=0.8,
)
plt.show()
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list4,
bins=range(0,36),
color="red",
alpha=0.8,
)
plt.show()
list_100 = []
multi_times(th_amount, 100, list_100)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(list_100,
color="green",
bins=range(275,425),
alpha=0.8,
)
plt.show()
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list4,
bins=range(2,36),
color="red",
alpha=1.0,
)
ax.hist(my_list3,
bins=range(2,36),
color="blue",
alpha=0.8,
)
ax.hist(my_list2,
bins=range(2,36),
color="green",
alpha=0.7,
)
ax.hist(my_list1,
bins=range(2,36),
color="yellow",
alpha=0.5,
)
ax.legend(["6 dices", "5 dices", "4 dices", "3 dices"])
plt.show()
import seaborn as sns
sns.distplot(my_list1, label='3 dices', kde=False)
sns.distplot(my_list2, label='4 dices', kde=False)
sns.distplot(my_list3, label='5 dices', kde=False)
sns.distplot(my_list4, label='6 dices', kde=False)
plt.legend() | code |
17132918/cell_12 | [
"image_output_1.png"
] | import matplotlib.pyplot as plt
import random
import random
import matplotlib
import matplotlib.pyplot as plt
def throw():
global x
x += random.randint(1, 6)
def multi_throw(dice_amount, list_name):
global x
x = 0
for i in range(dice_amount):
throw()
list_name.append(x)
def multi_times(time_amount, dice_amount, list_name):
for i in range(time_amount):
multi_throw(dice_amount, list_name)
x = 0
th_amount = 1000000
my_list1 = []
my_list2 = []
my_list3 = []
my_list4 = []
multi_times(th_amount, 3, my_list1)
multi_times(th_amount, 4, my_list2)
multi_times(th_amount, 5, my_list3)
multi_times(th_amount, 6, my_list4)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list3,
bins=range(0,36),
color="blue",
alpha=0.8,
)
plt.show()
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of '+str(th_amount)+' dice throws')
histy='step'
ax.hist(my_list4,
bins=range(0,36),
color="red",
alpha=0.8,
)
plt.show()
list_100 = []
multi_times(th_amount, 100, list_100)
fig, ax = plt.subplots()
plt.xlabel('score')
plt.ylabel('occurences')
plt.title('Histogram of ' + str(th_amount) + ' dice throws')
histy = 'step'
ax.hist(list_100, color='green', bins=range(275, 425), alpha=0.8)
plt.show() | code |
2020321/cell_21 | [
"text_plain_output_1.png",
"image_output_1.png"
] | from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
entire.Utilities.value_counts()
entire['DateSold'] = entire['YrSold'].astype(str) + '/' + entire['MoSold'].astype(str)
entire['DateSold'] = entire['DateSold'].apply(lambda x: datetime.strptime(x, '%Y/%m'))
title = 'Evolution of SalePrice with DateSold'
gpby = entire[entire.SalePrice.notnull()].groupby('DateSold')
gpby['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6))
title = 'Evolution of SalePrice with YearBuilt'
gpbyDate = entire.groupby('YearBuilt')
gpbyDate['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6))
entire[(entire.PoolArea > 0) & entire.PoolQC.isnull()][['OverallQual', 'OverallCond', 'PoolQC', 'PoolArea', 'SalePrice']]
for i in entire[(entire.PoolArea > 0) & entire.PoolQC.isnull()].index:
print('Replacement of PoolQC at index {}'.format(i))
entire.set_value(i, 'PoolQC', 'Fa') | code |
2020321/cell_9 | [
"text_html_output_1.png"
] | train.groupby('Utilities')['SalePrice'].agg(['median', 'mean', 'std']) | code |
2020321/cell_4 | [
"text_plain_output_1.png"
] | categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
print('{} categorical features:\n'.format(len(categ_feat)), categ_feat)
print('\n{} numerical features (float + int):\n'.format(len(num_feat)), num_feat)
print('\n{} numerical features (int only):\n'.format(len(int_feat)), int_feat)
features = categ_feat + num_feat | code |
2020321/cell_19 | [
"text_html_output_1.png"
] | from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
entire.Utilities.value_counts()
entire['DateSold'] = entire['YrSold'].astype(str) + '/' + entire['MoSold'].astype(str)
entire['DateSold'] = entire['DateSold'].apply(lambda x: datetime.strptime(x, '%Y/%m'))
title = 'Evolution of SalePrice with DateSold'
gpby = entire[entire.SalePrice.notnull()].groupby('DateSold')
gpby['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6))
title = 'Evolution of SalePrice with YearBuilt'
gpbyDate = entire.groupby('YearBuilt')
gpbyDate['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6))
entire[(entire.PoolArea > 0) & entire.PoolQC.isnull()][['OverallQual', 'OverallCond', 'PoolQC', 'PoolArea', 'SalePrice']] | code |
2020321/cell_7 | [
"text_html_output_1.png"
] | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
plot_features(categ_feat, 'SalePrice', entire[entire.SalePrice.notnull()]) | code |
2020321/cell_8 | [
"text_plain_output_1.png"
] | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
entire.Utilities.value_counts() | code |
2020321/cell_3 | [
"text_plain_output_1.png",
"image_output_1.png"
] | print('Total number of rows: {0}\n\t- {1} in training set\n\t- {2} in testing set\nNumber of features: {3}'.format(len(entire.index), len(train.index), len(test.index), len(train.columns))) | code |
2020321/cell_17 | [
"text_plain_output_1.png"
] | from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
entire.Utilities.value_counts()
entire['DateSold'] = entire['YrSold'].astype(str) + '/' + entire['MoSold'].astype(str)
entire['DateSold'] = entire['DateSold'].apply(lambda x: datetime.strptime(x, '%Y/%m'))
title = 'Evolution of SalePrice with DateSold'
gpby = entire[entire.SalePrice.notnull()].groupby('DateSold')
gpby['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6))
title = 'Evolution of SalePrice with YearBuilt'
gpbyDate = entire.groupby('YearBuilt')
gpbyDate['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6))
def show_nan(df, features, exclude='SalePrice'):
"""
Analyze a DataFrame and show if it contains missing values.
Print the names of features containing missing values sorted
by number of missing values
Arguments:
- df (DataFrame): dataset to analyse
- features (list): feature names to be analysed
- exclude (str): feature name not to be analysed
"""
features = [f for f in features if f != exclude]
list_feat = []
for feat in features:
if True in df[feat].isnull().values:
miss_val = df[feat].isnull().value_counts()[True]
prop = round(miss_val / df.Id.count(), 5)
list_feat.append((feat, miss_val, prop))
list_feat = sorted(list_feat, key=lambda x: x[-1], reverse=True)
show_nan(entire, features) | code |
2020321/cell_14 | [
"image_output_1.png"
] | from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
entire.Utilities.value_counts()
entire['DateSold'] = entire['YrSold'].astype(str) + '/' + entire['MoSold'].astype(str)
entire['DateSold'] = entire['DateSold'].apply(lambda x: datetime.strptime(x, '%Y/%m'))
title = 'Evolution of SalePrice with DateSold'
gpby = entire[entire.SalePrice.notnull()].groupby('DateSold')
gpby['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6))
title = 'Evolution of SalePrice with YearBuilt'
gpbyDate = entire.groupby('YearBuilt')
gpbyDate['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6)) | code |
2020321/cell_10 | [
"text_plain_output_1.png"
] | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
entire.Utilities.value_counts()
plot_features(num_feat, 'SalePrice', entire[entire.SalePrice.notnull()]) | code |
2020321/cell_12 | [
"text_plain_output_1.png"
] | from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
categ_feat = sorted(list(entire.dtypes[entire.dtypes == 'object'].index))
num_feat = sorted(list(entire.dtypes[(entire.dtypes == 'int64') | (entire.dtypes == 'float64')].index))
int_feat = sorted(list(entire.dtypes[entire.dtypes == 'int64'].index))
features = categ_feat + num_feat
def plot_features(x_list, y_name, df, threshold=0.5):
"""
Generate a figure with an axe per plot, each axe plotting y_name
feature function of numerical or categorical features in x_list.
Print the feature names and corresponding regression coefficients
ordered by coefficient values
Arguments:
- x_list (list): list of feature names for x-axis
- y_name (str): feature name for y-axis
- df (pandas.DataFrame): dataset containing the data to plot
- threshold (float): threshold value for regression coefficient
printing
"""
colors = sns.color_palette(n_colors=len(x_list))
list_tup = [] # List of (feature_name, reg_coef)
if not len(x_list)%2:
row_nb = int(len(x_list)/2)
else:
row_nb = int(len(x_list)/2) + 1
size_y = row_nb * 5
fig = plt.figure(figsize=(15, size_y*1.05))
i = 1
for x_name in x_list:
ax = fig.add_subplot(row_nb, 2, i)
if df[x_name].dtypes == 'object': # Categorical feature
sns.boxplot(x=x_name, y=y_name, data=df, ax=ax)
else: # Numerical feature
sns.regplot(x=x_name, y=y_name, data=df, ax=ax,
color=colors[i-1])
corr = np.corrcoef(df[x_name], df[y_name])[0, 1]
list_tup.append((x_name, corr))
ax.set_title('Regression coef: {:.2f}'.format(corr))
i += 1
list_tup = [tup for tup in list_tup if tup[1] >= threshold]
list_tup = sorted(list_tup, key=lambda x: x[1], reverse=True)
for tup in list_tup:
print("Regression coefficient for {0}:\t{1:.2f}"
.format(tup[0], tup[1]))
entire.Utilities.value_counts()
entire['DateSold'] = entire['YrSold'].astype(str) + '/' + entire['MoSold'].astype(str)
entire['DateSold'] = entire['DateSold'].apply(lambda x: datetime.strptime(x, '%Y/%m'))
title = 'Evolution of SalePrice with DateSold'
gpby = entire[entire.SalePrice.notnull()].groupby('DateSold')
gpby['SalePrice'].agg(['median', 'mean', 'std']).plot(grid=True, title=title, figsize=(8, 6)) | code |
48165213/cell_20 | [
"text_html_output_1.png"
] | import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers,
values= top_10_publishers.values,
names= top_10_publishers.index,
title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
def top_sales(df, region):
if region == 'JP_Sales':
japan = games.groupby('Name')['JP_Sales'].sum().reset_index().sort_values('JP_Sales', ascending=False).head(10)
return japan
elif region == 'EU_Sales':
eu = games.groupby('Name')['EU_Sales'].sum().reset_index().sort_values('EU_Sales', ascending=False).head(10)
return eu
elif region == 'NA_Sales':
na = games.groupby('Name')['NA_Sales'].sum().reset_index().sort_values('NA_Sales', ascending=False).head(10)
return na
elif region == 'Global_Sales':
globe = games.groupby('Name')['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
return globe
else:
other = games.groupby('Name')['Other_Sales'].sum().reset_index().sort_values('Other_Sales', ascending=False).head(10)
return other
top10_JP_sales = top_sales(games, 'JP_Sales')
top10_EU_sales = top_sales(games, 'EU_Sales')
top10_NA_sales = top_sales(games, 'NA_Sales')
fig = go.Figure(data=[go.Bar(x=top10_JP_sales.Name, y=top10_JP_sales.JP_Sales)], layout_title_text='Top 10 Sales Games In Japan')
fig = go.Figure(data=[go.Bar(x=top10_EU_sales.Name, y=top10_EU_sales.EU_Sales)], layout_title_text='Top 10 Sales Games In EU')
fig = go.Figure(data=[go.Bar(x=top10_NA_sales.Name, y=top10_NA_sales.NA_Sales)], layout_title_text='Top 10 Sales Games In NA')
fig.show() | code |
48165213/cell_26 | [
"text_html_output_1.png"
] | import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers,
values= top_10_publishers.values,
names= top_10_publishers.index,
title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
def top_sales(df, region):
if region == 'JP_Sales':
japan = games.groupby('Name')['JP_Sales'].sum().reset_index().sort_values('JP_Sales', ascending=False).head(10)
return japan
elif region == 'EU_Sales':
eu = games.groupby('Name')['EU_Sales'].sum().reset_index().sort_values('EU_Sales', ascending=False).head(10)
return eu
elif region == 'NA_Sales':
na = games.groupby('Name')['NA_Sales'].sum().reset_index().sort_values('NA_Sales', ascending=False).head(10)
return na
elif region == 'Global_Sales':
globe = games.groupby('Name')['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
return globe
else:
other = games.groupby('Name')['Other_Sales'].sum().reset_index().sort_values('Other_Sales', ascending=False).head(10)
return other
top10_JP_sales = top_sales(games, 'JP_Sales')
top10_EU_sales = top_sales(games, 'EU_Sales')
top10_NA_sales = top_sales(games, 'NA_Sales')
top10_Global_sales = top_sales(games, 'Global_Sales')
top10_Other_sales = top_sales(games, 'Other_Sales')
fig = go.Figure(data=[go.Bar(x=top10_JP_sales.Name, y=top10_JP_sales.JP_Sales)], layout_title_text='Top 10 Sales Games In Japan')
fig = go.Figure(data=[go.Bar(x=top10_EU_sales.Name, y=top10_EU_sales.EU_Sales)], layout_title_text='Top 10 Sales Games In EU')
fig = go.Figure(data=[go.Bar(x=top10_NA_sales.Name, y=top10_NA_sales.NA_Sales)], layout_title_text='Top 10 Sales Games In NA')
fig = go.Figure(data=[go.Bar(x=top10_Global_sales.Name, y=top10_Global_sales.Global_Sales)], layout_title_text='Top 10 Sales Games Global')
fig = go.Figure(data=[go.Bar(x=top10_Other_sales.Name, y=top10_Other_sales.Other_Sales)], layout_title_text='Top 10 Sales Games Other')
publication_distr = games.Year.value_counts().sort_values(ascending=False)
fig = px.bar(publication_distr, x=publication_distr.index, y=publication_distr.values, title='Year of Games Releasing & Distribution')
fig.show() | code |
48165213/cell_1 | [
"text_plain_output_1.png"
] | import numpy as np
import pandas as pd
from IPython.display import display
import seaborn as sns
import plotly
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objs as go
plotly.offline.init_notebook_mode(connected=True)
from plotly.subplots import make_subplots
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename)) | code |
48165213/cell_7 | [
"text_html_output_1.png"
] | import pandas as pd
import plotly.express as px
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers, values=top_10_publishers.values, names=top_10_publishers.index, title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show() | code |
48165213/cell_18 | [
"image_output_1.png"
] | import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers,
values= top_10_publishers.values,
names= top_10_publishers.index,
title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
def top_sales(df, region):
if region == 'JP_Sales':
japan = games.groupby('Name')['JP_Sales'].sum().reset_index().sort_values('JP_Sales', ascending=False).head(10)
return japan
elif region == 'EU_Sales':
eu = games.groupby('Name')['EU_Sales'].sum().reset_index().sort_values('EU_Sales', ascending=False).head(10)
return eu
elif region == 'NA_Sales':
na = games.groupby('Name')['NA_Sales'].sum().reset_index().sort_values('NA_Sales', ascending=False).head(10)
return na
elif region == 'Global_Sales':
globe = games.groupby('Name')['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
return globe
else:
other = games.groupby('Name')['Other_Sales'].sum().reset_index().sort_values('Other_Sales', ascending=False).head(10)
return other
top10_JP_sales = top_sales(games, 'JP_Sales')
top10_EU_sales = top_sales(games, 'EU_Sales')
fig = go.Figure(data=[go.Bar(x=top10_JP_sales.Name, y=top10_JP_sales.JP_Sales)], layout_title_text='Top 10 Sales Games In Japan')
fig = go.Figure(data=[go.Bar(x=top10_EU_sales.Name, y=top10_EU_sales.EU_Sales)], layout_title_text='Top 10 Sales Games In EU')
fig.show() | code |
48165213/cell_28 | [
"text_html_output_1.png"
] | import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers,
values= top_10_publishers.values,
names= top_10_publishers.index,
title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
def top_sales(df, region):
if region == 'JP_Sales':
japan = games.groupby('Name')['JP_Sales'].sum().reset_index().sort_values('JP_Sales', ascending=False).head(10)
return japan
elif region == 'EU_Sales':
eu = games.groupby('Name')['EU_Sales'].sum().reset_index().sort_values('EU_Sales', ascending=False).head(10)
return eu
elif region == 'NA_Sales':
na = games.groupby('Name')['NA_Sales'].sum().reset_index().sort_values('NA_Sales', ascending=False).head(10)
return na
elif region == 'Global_Sales':
globe = games.groupby('Name')['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
return globe
else:
other = games.groupby('Name')['Other_Sales'].sum().reset_index().sort_values('Other_Sales', ascending=False).head(10)
return other
top10_JP_sales = top_sales(games, 'JP_Sales')
top10_EU_sales = top_sales(games, 'EU_Sales')
top10_NA_sales = top_sales(games, 'NA_Sales')
top10_Global_sales = top_sales(games, 'Global_Sales')
top10_Other_sales = top_sales(games, 'Other_Sales')
fig = go.Figure(data=[go.Bar(x=top10_JP_sales.Name, y=top10_JP_sales.JP_Sales)], layout_title_text='Top 10 Sales Games In Japan')
fig = go.Figure(data=[go.Bar(x=top10_EU_sales.Name, y=top10_EU_sales.EU_Sales)], layout_title_text='Top 10 Sales Games In EU')
fig = go.Figure(data=[go.Bar(x=top10_NA_sales.Name, y=top10_NA_sales.NA_Sales)], layout_title_text='Top 10 Sales Games In NA')
fig = go.Figure(data=[go.Bar(x=top10_Global_sales.Name, y=top10_Global_sales.Global_Sales)], layout_title_text='Top 10 Sales Games Global')
fig = go.Figure(data=[go.Bar(x=top10_Other_sales.Name, y=top10_Other_sales.Other_Sales)], layout_title_text='Top 10 Sales Games Other')
publication_distr = games.Year.value_counts().sort_values(ascending=False)
fig = px.bar(publication_distr,
x=publication_distr.index,
y=publication_distr.values,
title= "Year of Games Releasing & Distribution")
fig.show()
top10_sales_games = games.groupby(['Name', 'Year'])['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
fig = px.pie(top10_sales_games, values=top10_sales_games.Year, names=top10_sales_games.Name, title='Top 10 Worldwide Sales Games Globally')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show() | code |
48165213/cell_16 | [
"text_html_output_1.png"
] | import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers,
values= top_10_publishers.values,
names= top_10_publishers.index,
title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
def top_sales(df, region):
if region == 'JP_Sales':
japan = games.groupby('Name')['JP_Sales'].sum().reset_index().sort_values('JP_Sales', ascending=False).head(10)
return japan
elif region == 'EU_Sales':
eu = games.groupby('Name')['EU_Sales'].sum().reset_index().sort_values('EU_Sales', ascending=False).head(10)
return eu
elif region == 'NA_Sales':
na = games.groupby('Name')['NA_Sales'].sum().reset_index().sort_values('NA_Sales', ascending=False).head(10)
return na
elif region == 'Global_Sales':
globe = games.groupby('Name')['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
return globe
else:
other = games.groupby('Name')['Other_Sales'].sum().reset_index().sort_values('Other_Sales', ascending=False).head(10)
return other
top10_JP_sales = top_sales(games, 'JP_Sales')
fig = go.Figure(data=[go.Bar(x=top10_JP_sales.Name, y=top10_JP_sales.JP_Sales)], layout_title_text='Top 10 Sales Games In Japan')
fig.show() | code |
48165213/cell_3 | [
"text_html_output_1.png"
] | import pandas as pd
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
games | code |
48165213/cell_24 | [
"text_html_output_1.png"
] | import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers,
values= top_10_publishers.values,
names= top_10_publishers.index,
title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
def top_sales(df, region):
if region == 'JP_Sales':
japan = games.groupby('Name')['JP_Sales'].sum().reset_index().sort_values('JP_Sales', ascending=False).head(10)
return japan
elif region == 'EU_Sales':
eu = games.groupby('Name')['EU_Sales'].sum().reset_index().sort_values('EU_Sales', ascending=False).head(10)
return eu
elif region == 'NA_Sales':
na = games.groupby('Name')['NA_Sales'].sum().reset_index().sort_values('NA_Sales', ascending=False).head(10)
return na
elif region == 'Global_Sales':
globe = games.groupby('Name')['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
return globe
else:
other = games.groupby('Name')['Other_Sales'].sum().reset_index().sort_values('Other_Sales', ascending=False).head(10)
return other
top10_JP_sales = top_sales(games, 'JP_Sales')
top10_EU_sales = top_sales(games, 'EU_Sales')
top10_NA_sales = top_sales(games, 'NA_Sales')
top10_Global_sales = top_sales(games, 'Global_Sales')
top10_Other_sales = top_sales(games, 'Other_Sales')
fig = go.Figure(data=[go.Bar(x=top10_JP_sales.Name, y=top10_JP_sales.JP_Sales)], layout_title_text='Top 10 Sales Games In Japan')
fig = go.Figure(data=[go.Bar(x=top10_EU_sales.Name, y=top10_EU_sales.EU_Sales)], layout_title_text='Top 10 Sales Games In EU')
fig = go.Figure(data=[go.Bar(x=top10_NA_sales.Name, y=top10_NA_sales.NA_Sales)], layout_title_text='Top 10 Sales Games In NA')
fig = go.Figure(data=[go.Bar(x=top10_Global_sales.Name, y=top10_Global_sales.Global_Sales)], layout_title_text='Top 10 Sales Games Global')
fig = go.Figure(data=[go.Bar(x=top10_Other_sales.Name, y=top10_Other_sales.Other_Sales)], layout_title_text='Top 10 Sales Games Other')
fig.show() | code |
48165213/cell_22 | [
"text_html_output_1.png"
] | import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
top_10_publishers = games.Publisher.value_counts().sort_values(ascending=False).head(10)
fig = px.pie(top_10_publishers,
values= top_10_publishers.values,
names= top_10_publishers.index,
title='Top 10 Games Publishers')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
def top_sales(df, region):
if region == 'JP_Sales':
japan = games.groupby('Name')['JP_Sales'].sum().reset_index().sort_values('JP_Sales', ascending=False).head(10)
return japan
elif region == 'EU_Sales':
eu = games.groupby('Name')['EU_Sales'].sum().reset_index().sort_values('EU_Sales', ascending=False).head(10)
return eu
elif region == 'NA_Sales':
na = games.groupby('Name')['NA_Sales'].sum().reset_index().sort_values('NA_Sales', ascending=False).head(10)
return na
elif region == 'Global_Sales':
globe = games.groupby('Name')['Global_Sales'].sum().reset_index().sort_values('Global_Sales', ascending=False).head(10)
return globe
else:
other = games.groupby('Name')['Other_Sales'].sum().reset_index().sort_values('Other_Sales', ascending=False).head(10)
return other
top10_JP_sales = top_sales(games, 'JP_Sales')
top10_EU_sales = top_sales(games, 'EU_Sales')
top10_NA_sales = top_sales(games, 'NA_Sales')
top10_Global_sales = top_sales(games, 'Global_Sales')
fig = go.Figure(data=[go.Bar(x=top10_JP_sales.Name, y=top10_JP_sales.JP_Sales)], layout_title_text='Top 10 Sales Games In Japan')
fig = go.Figure(data=[go.Bar(x=top10_EU_sales.Name, y=top10_EU_sales.EU_Sales)], layout_title_text='Top 10 Sales Games In EU')
fig = go.Figure(data=[go.Bar(x=top10_NA_sales.Name, y=top10_NA_sales.NA_Sales)], layout_title_text='Top 10 Sales Games In NA')
fig = go.Figure(data=[go.Bar(x=top10_Global_sales.Name, y=top10_Global_sales.Global_Sales)], layout_title_text='Top 10 Sales Games Global')
fig.show() | code |
48165213/cell_5 | [
"text_html_output_1.png"
] | import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
games = pd.read_csv('/kaggle/input/videogamesales/vgsales.csv')
sns.set_style('whitegrid')
fig, ax1 = plt.subplots(figsize=(20, 11))
plt.title('Number of different games per game platforms')
sns.countplot(x='Platform', data=games, ax=ax1)
plt.show() | code |
329717/cell_2 | [
"text_plain_output_1.png"
] | import pandas as pd
import pandas as pd
df = pd.read_csv('../input/people.csv')
print(df.head()) | code |
128026337/cell_13 | [
"image_output_1.png"
] | import matplotlib.pyplot as plt
import networkx as nx
def knight_moves(pos):
x, y = pos
moves = [(x + 1, y + 2), (x + 1, y - 2), (x - 1, y + 2), (x - 1, y - 2), (x + 2, y + 1), (x + 2, y - 1), (x - 2, y + 1), (x - 2, y - 1)]
return [(a, b) for a, b in moves if 0 <= a < 8 and 0 <= b < 8]
def create_chessboard_graph():
chess_graph = nx.Graph()
for x in range(8):
for y in range(8):
pos = (x, y)
chess_graph.add_node(pos, pos=pos)
for move in knight_moves(pos):
chess_graph.add_edge(pos, move)
return chess_graph
def draw_chessboard_graph(chess_graph):
pos = nx.get_node_attributes(chess_graph, 'pos')
def create_maze_graph():
maze_graph = nx.Graph()
maze_graph.add_nodes_from(range(1, 22))
maze_graph.add_edges_from([(1, 2), (2, 3), (2, 5), (5, 4), (5, 6), (6, 7), (6, 9), (9, 8), (9, 10), (10, 11), (10, 13), (13, 12), (13, 14), (14, 17), (14, 15), (14, 21), (17, 16), (17, 18), (21, 19), (21, 22), (18, 20), (18, 21)])
return maze_graph
def draw_maze_graph(maze_graph):
pos = nx.spring_layout(maze_graph, seed=1)
maze_graph = create_maze_graph()
def create_water_vessels_graph():
vessels_graph = nx.DiGraph()
states = [(8, 0, 0), (3, 5, 0), (3, 2, 3), (6, 2, 0), (6, 0, 2), (1, 5, 2), (1, 4, 3), (4, 4, 0)]
vessels_graph.add_nodes_from(states)
edges = [((8, 0, 0), (3, 5, 0)), ((3, 5, 0), (0, 5, 3)), ((0, 5, 3), (3, 2, 3)), ((3, 2, 3), (6, 2, 0)), ((6, 2, 0), (6, 0, 2)), ((6, 0, 2), (1, 5, 2)), ((1, 5, 2), (1, 4, 3)), ((1, 4, 3), (4, 4, 0))]
vessels_graph.add_edges_from(edges)
return vessels_graph
def draw_water_jug_graph(vessels_graph):
pos = nx.spring_layout(vessels_graph, seed=1)
nx.draw(vessels_graph, pos, with_labels=True, node_size=1600)
nx.draw_networkx_labels(vessels_graph, {x: (y[0], y[1] - 0.1) for x, y in pos.items()}, labels=dict(vessels_graph.degree()), font_size=10)
plt.show()
draw_water_jug_graph(create_water_vessels_graph()) | code |
128026337/cell_8 | [
"image_output_1.png"
] | import matplotlib.pyplot as plt
import networkx as nx
def knight_moves(pos):
x, y = pos
moves = [(x + 1, y + 2), (x + 1, y - 2), (x - 1, y + 2), (x - 1, y - 2), (x + 2, y + 1), (x + 2, y - 1), (x - 2, y + 1), (x - 2, y - 1)]
return [(a, b) for a, b in moves if 0 <= a < 8 and 0 <= b < 8]
def create_chessboard_graph():
chess_graph = nx.Graph()
for x in range(8):
for y in range(8):
pos = (x, y)
chess_graph.add_node(pos, pos=pos)
for move in knight_moves(pos):
chess_graph.add_edge(pos, move)
return chess_graph
def draw_chessboard_graph(chess_graph):
pos = nx.get_node_attributes(chess_graph, 'pos')
def create_maze_graph():
maze_graph = nx.Graph()
maze_graph.add_nodes_from(range(1, 22))
maze_graph.add_edges_from([(1, 2), (2, 3), (2, 5), (5, 4), (5, 6), (6, 7), (6, 9), (9, 8), (9, 10), (10, 11), (10, 13), (13, 12), (13, 14), (14, 17), (14, 15), (14, 21), (17, 16), (17, 18), (21, 19), (21, 22), (18, 20), (18, 21)])
return maze_graph
def draw_maze_graph(maze_graph):
pos = nx.spring_layout(maze_graph, seed=1)
nx.draw(maze_graph, pos, with_labels=True, node_size=500)
nx.draw_networkx_labels(maze_graph, {x: (y[0], y[1] - 0.08) for x, y in pos.items()}, labels=dict(maze_graph.degree()), font_size=10)
plt.show()
maze_graph = create_maze_graph()
draw_maze_graph(maze_graph) | code |
128026337/cell_10 | [
"image_output_1.png"
] | import matplotlib.pyplot as plt
import networkx as nx
def knight_moves(pos):
x, y = pos
moves = [(x + 1, y + 2), (x + 1, y - 2), (x - 1, y + 2), (x - 1, y - 2), (x + 2, y + 1), (x + 2, y - 1), (x - 2, y + 1), (x - 2, y - 1)]
return [(a, b) for a, b in moves if 0 <= a < 8 and 0 <= b < 8]
def create_chessboard_graph():
chess_graph = nx.Graph()
for x in range(8):
for y in range(8):
pos = (x, y)
chess_graph.add_node(pos, pos=pos)
for move in knight_moves(pos):
chess_graph.add_edge(pos, move)
return chess_graph
def draw_chessboard_graph(chess_graph):
pos = nx.get_node_attributes(chess_graph, 'pos')
def create_maze_graph():
maze_graph = nx.Graph()
maze_graph.add_nodes_from(range(1, 22))
maze_graph.add_edges_from([(1, 2), (2, 3), (2, 5), (5, 4), (5, 6), (6, 7), (6, 9), (9, 8), (9, 10), (10, 11), (10, 13), (13, 12), (13, 14), (14, 17), (14, 15), (14, 21), (17, 16), (17, 18), (21, 19), (21, 22), (18, 20), (18, 21)])
return maze_graph
def draw_maze_graph(maze_graph):
pos = nx.spring_layout(maze_graph, seed=1)
maze_graph = create_maze_graph()
maze_graph.number_of_edges() * 2 | code |
128026337/cell_5 | [
"text_plain_output_1.png"
] | import matplotlib.pyplot as plt
import networkx as nx
def knight_moves(pos):
x, y = pos
moves = [(x + 1, y + 2), (x + 1, y - 2), (x - 1, y + 2), (x - 1, y - 2), (x + 2, y + 1), (x + 2, y - 1), (x - 2, y + 1), (x - 2, y - 1)]
return [(a, b) for a, b in moves if 0 <= a < 8 and 0 <= b < 8]
def create_chessboard_graph():
chess_graph = nx.Graph()
for x in range(8):
for y in range(8):
pos = (x, y)
chess_graph.add_node(pos, pos=pos)
for move in knight_moves(pos):
chess_graph.add_edge(pos, move)
return chess_graph
def draw_chessboard_graph(chess_graph):
pos = nx.get_node_attributes(chess_graph, 'pos')
nx.draw(chess_graph, pos, node_size=500, with_labels=True)
nx.draw_networkx_labels(chess_graph, {x: (y[0], y[1] - 0.4) for x, y in pos.items()}, labels=dict(chess_graph.degree()), font_size=10)
plt.show()
draw_chessboard_graph(create_chessboard_graph()) | code |
128027620/cell_21 | [
"image_output_1.png"
] | import pandas as pd
import seaborn as sns
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
train.full_text.apply(lambda x: get_length_of_text(x)).hist()
train.isna().sum()
colormap = sns.color_palette('Blues')
train.head() | code |
128027620/cell_13 | [
"image_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
train.full_text.apply(lambda x: get_length_of_text(x)).hist() | code |
128027620/cell_9 | [
"text_plain_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
train.phraseology.hist() | code |
128027620/cell_25 | [
"image_output_1.png"
] | import pandas as pd
import seaborn as sns
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
train.full_text.apply(lambda x: get_length_of_text(x)).hist()
train.isna().sum()
colormap = sns.color_palette('Blues')
df = train.copy()
target_vars = ['cohesion', 'syntax', 'vocabulary', 'phraseology', 'grammar', 'conventions']
df.head() | code |
128027620/cell_23 | [
"text_plain_output_1.png"
] | from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
import seaborn as sns
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
train.full_text.apply(lambda x: get_length_of_text(x)).hist()
train.isna().sum()
colormap = sns.color_palette('Blues')
df = train.copy()
target_vars = ['cohesion', 'syntax', 'vocabulary', 'phraseology', 'grammar', 'conventions']
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(smooth_idf=True, sublinear_tf=True, max_features=5000)
vectorizer.fit(raw_documents=train.full_text) | code |
128027620/cell_6 | [
"text_plain_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
train.cohesion.hist() | code |
128027620/cell_26 | [
"text_plain_output_1.png"
] | from sklearn.feature_extraction.text import TfidfVectorizer
from tqdm import tqdm
import numpy as np
import pandas as pd
import seaborn as sns
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
train.full_text.apply(lambda x: get_length_of_text(x)).hist()
train.isna().sum()
colormap = sns.color_palette('Blues')
df = train.copy()
target_vars = ['cohesion', 'syntax', 'vocabulary', 'phraseology', 'grammar', 'conventions']
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(smooth_idf=True, sublinear_tf=True, max_features=5000)
vectorizer.fit(raw_documents=train.full_text)
def extract_vectors(x):
vecs = vectorizer.transform(x)
return vecs.toarray().flatten()
df['vecs'] = train.full_text.apply(lambda x: extract_vectors([x]))
feature_set = []
for i, row in tqdm(df.iterrows(), total=len(df)):
vecs = row['vecs']
vals = row[target_vars].astype(float)
features = np.hstack([vecs, vals]).flatten()
feature_set.append(features)
feature_set = np.array(feature_set) | code |
128027620/cell_11 | [
"image_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
train.conventions.hist() | code |
128027620/cell_7 | [
"text_html_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
train.syntax.hist() | code |
128027620/cell_8 | [
"application_vnd.jupyter.stderr_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
train.vocabulary.hist() | code |
128027620/cell_16 | [
"image_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
train.full_text.apply(lambda x: get_length_of_text(x)).hist()
train.isna().sum() | code |
128027620/cell_3 | [
"image_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
train.head() | code |
128027620/cell_17 | [
"image_output_1.png"
] | import pandas as pd
import seaborn as sns
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
train.full_text.apply(lambda x: get_length_of_text(x)).hist()
train.isna().sum()
colormap = sns.color_palette('Blues')
sns.heatmap(train.corr(), annot=True, cmap=colormap) | code |
128027620/cell_10 | [
"text_html_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
train.grammar.hist() | code |
128027620/cell_12 | [
"image_output_1.png"
] | import pandas as pd
train = pd.read_csv('../input/feedback-prize-english-language-learning/train.csv')
test = pd.read_csv('../input/feedback-prize-english-language-learning/test.csv')
ss = pd.read_csv('../input/feedback-prize-english-language-learning/sample_submission.csv')
def get_length_of_text(x):
return len(x)
print(f'Average length: {train.full_text.apply(lambda x: get_length_of_text(x)).mean():0.2f}')
print(f'Std length: {train.full_text.apply(lambda x: get_length_of_text(x)).std():0.2f}')
print(f'Min length: {train.full_text.apply(lambda x: get_length_of_text(x)).min():0.2f}')
print(f'Max length: {train.full_text.apply(lambda x: get_length_of_text(x)).max():0.2f}') | code |
129035281/cell_21 | [
"text_html_output_1.png"
] | import pandas as pd
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.describe() | code |
129035281/cell_34 | [
"text_plain_output_1.png"
] | import pandas as pd
import pingouin as pg
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.dtypes
pl = df[(df['League'] == 'Premier League') & (df['Rank'] == 1)][['League', 'Team', 'Start Season', 'End Season', 'Points', 'Wins']].reset_index(drop=True)
ll = df[(df['League'] == 'La Liga') & (df['Rank'] == 1)][['League', 'Team', 'Start Season', 'End Season', 'Points', 'Wins']].reset_index(drop=True)
print(f"Premier League Winner Points in 2009-2022 are normal -> {pg.normality(pl.Points.values)['normal'].values[0]}")
print(f"LaLiga Winner Points in 2009-2022 are normal -> {pg.normality(ll.Points.values)['normal'].values[0]}") | code |
129035281/cell_23 | [
"text_plain_output_1.png"
] | import pandas as pd
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.dtypes
df.info() | code |
129035281/cell_20 | [
"text_html_output_1.png"
] | import pandas as pd
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.tail() | code |
129035281/cell_40 | [
"text_html_output_1.png"
] | import pandas as pd
import pingouin as pg
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.dtypes
pl = df[(df['League'] == 'Premier League') & (df['Rank'] == 1)][['League', 'Team', 'Start Season', 'End Season', 'Points', 'Wins']].reset_index(drop=True)
ll = df[(df['League'] == 'La Liga') & (df['Rank'] == 1)][['League', 'Team', 'Start Season', 'End Season', 'Points', 'Wins']].reset_index(drop=True)
pg.ttest(ll.Points.values, pl.Points.values, correction=False, alternative='greater') | code |
129035281/cell_11 | [
"text_html_output_1.png"
] | !wget http://bit.ly/3ZLyF82 -O CSS.css -q
from IPython.core.display import HTML
with open('./CSS.css', 'r') as file:
custom_css = file.read()
HTML(custom_css) | code |
129035281/cell_19 | [
"text_html_output_1.png"
] | import pandas as pd
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.head() | code |
129035281/cell_15 | [
"application_vnd.jupyter.stderr_output_1.png"
] | import pandas as pd
import pingouin as pg | code |
129035281/cell_31 | [
"text_plain_output_1.png"
] | import pandas as pd
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.dtypes
pl = df[(df['League'] == 'Premier League') & (df['Rank'] == 1)][['League', 'Team', 'Start Season', 'End Season', 'Points', 'Wins']].reset_index(drop=True)
ll = df[(df['League'] == 'La Liga') & (df['Rank'] == 1)][['League', 'Team', 'Start Season', 'End Season', 'Points', 'Wins']].reset_index(drop=True)
print(f"La Liga Winners Average Points in 2009-2022 is -> {round(ll['Points'].mean(), 2)}")
print(f"Premier League Winners Average Points in 2009-2022 is -> {round(pl['Points'].mean(), 2)}") | code |
129035281/cell_14 | [
"text_plain_output_1.png"
] | ! pip install pingouin | code |
129035281/cell_22 | [
"text_plain_output_1.png"
] | import pandas as pd
df = pd.read_csv('/kaggle/input/performance-data-on-football-teams-09-to-22/Complete Dataset 2.csv')
df.dtypes | code |
49124084/cell_4 | [
"text_html_output_1.png"
] | import numpy as np # linear algebra
import pandas as pd
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import pandas as pd
data = pd.read_csv('../input/twitter-train/train.txt', delimiter='\n', header=None)
data_array = data.to_numpy()
x_array = np.reshape(data_array, (-1, 3))
print(x_array)
column = ['Tweet', 'Target', 'Sentiment']
data = pd.DataFrame(data=x_array, columns=column)
data | code |
49124084/cell_6 | [
"text_plain_output_1.png"
] | import numpy as np # linear algebra
import pandas as pd
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import pandas as pd
data = pd.read_csv('../input/twitter-train/train.txt', delimiter='\n', header=None)
data_array = data.to_numpy()
x_array = np.reshape(data_array, (-1, 3))
column = ['Tweet', 'Target', 'Sentiment']
data = pd.DataFrame(data=x_array, columns=column)
data
my_dataset = data
my_dataset = my_dataset.drop(['Target', 'Sentiment'], axis=1)
my_target = data.drop(['Tweet', 'Sentiment'], axis=1)
for i in my_dataset.index:
x = my_dataset['Tweet'][i].find('$T$')
s = my_dataset['Tweet'][1].replace('$T$', my_target['Target'][0])
j = 0
my_targetless_tweet = []
for i in range(6248):
my_targetless_tweet.insert(i, my_dataset['Tweet'][i].replace('$T$', my_target['Target'][j]))
j = j + 1
my_targetless_tweet = pd.DataFrame(my_targetless_tweet)
my_targetless_tweet
targetless_tweet = my_targetless_tweet.to_numpy()
new_array = np.reshape(targetless_tweet, (-1, 1))
print(new_array)
column = ['Tweet (no target)']
no_target_data = pd.DataFrame(data=new_array, columns=column)
no_target_data | code |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.