markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
* It creates another variable. | cities.projection2020 | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Specifying a `Series` as a new columns cause its values to be added according to the `DataFrame`'s index: | populationIn2000 = pd.Series([11076840, 3889199, 3431204, 2150571, 1430539])
populationIn2000
cities['population_2000'] = populationIn2000
cities | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Other Python data structures (ones without an index) need to be the same length as the `DataFrame`: | populationIn2007 = [12573836, 4466756, 3739353, 2439876]
cities['population_2007'] = populationIn2007 | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can use `del` to remove columns, in the same way `dict` entries can be removed: | cities
del cities['population_2000']
cities | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can extract the underlying data as a simple `ndarray` by accessing the `values` attribute: | cities.values | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Notice that because of the mix of string and integer (and could be`NaN`) values, the dtype of the array is `object`. * The dtype will automatically be chosen to be as general as needed to accomodate all the columns. | df = pd.DataFrame({'integers': [1,2,3], 'floatNumbers':[0.5, -1.25, 2.5]})
df
print(df.values.dtype)
df.values | float64
| Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Pandas uses a custom data structure to represent the indices of Series and DataFrames. | cities.index | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Index objects are immutable: | cities.index[0] = 15 | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* This is so that Index objects can be shared between data structures without fear that they will be changed.* That means you can move, copy your meaningful labels to other `DataFrames` | cities
cities.index = population2.index
cities | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Importing data * A key, but often under appreciated, step in data analysis is importing the data that we wish to analyze.* Though it is easy to load basic data structures into Python using built-in tools or those provided by packages like NumPy, it is non-trivial to import structured data well, and to easily convert t... | !cat data/population.csv | Provinces;2000;2001;2002;2003;2004;2005;2006;2007;2008;2009;2010;2011;2012;2013;2014;2015;2016;2017
Total;64729501;65603160;66401851;67187251;68010215;68860539;69729967;70586256;71517100;72561312;73722988;74724269;75627384;76667864;77695904;78741053;79814871;80810525
Adana;1879695;1899324;1916637;1933428;1951142;19... | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* This table can be read into a DataFrame using `read_csv`: | populationDF = pd.read_csv("data/population.csv")
populationDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Notice that `read_csv` automatically considered the first row in the file to be a header row.* We can override default behavior by customizing some the arguments, like `header`, `names` or `index_col`. * `read_csv` is just a convenience function for `read_table`, since csv is such a common format: | pd.set_option('max_columns', 5)
populationDF = pd.read_table("data/population_missing.csv", sep=';')
populationDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* The `sep` argument can be customized as needed to accomodate arbitrary separators. * If we have sections of data that we do not wish to import (for example, in this example empty rows), we can populate the `skiprows` argument: | populationDF = pd.read_csv("data/population_missing.csv", sep=';', skiprows=[1,2])
populationDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* For a more useful index, we can specify the first column, which provide a unique index to the data. | populationDF = pd.read_csv("data/population.csv", sep=';', index_col='Provinces')
populationDF.index | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Conversely, if we only want to import a small number of rows from, say, a very large data file we can use `nrows`: | pd.read_csv("data/population.csv", sep=';', nrows=4) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Most real-world data is incomplete, with values missing due to incomplete observation, data entry or transcription error, or other reasons. Pandas will automatically recognize and parse common missing data indicators, including `NA`, `NaN`, `NULL`. | pd.read_csv("data/population_missing.csv", sep=';').head(10) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Above, Pandas recognized `NaN` and an empty field as missing data. | pd.isnull(pd.read_csv("data/population_missing.csv", sep=';')).head(10) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Microsoft Excel * Since so much financial and scientific data ends up in Excel spreadsheets, Pandas' ability to directly import Excel spreadsheets is valuable. * This support is contingent on having one or two dependencies (depending on what version of Excel file is being imported) installed: `xlrd` and `openpyxl`.* I... | excel_file = pd.ExcelFile('data/population.xlsx')
excel_file | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Then, since modern spreadsheets consist of one or more "sheets", we parse the sheet with the data of interest: | excelDf = excel_file.parse("Sheet 1 ")
excelDf | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Also, there is a `read_excel` conveneince function in Pandas that combines these steps into a single call: | excelDf2 = pd.read_excel('data/population.xlsx', sheet_name='Sheet 1 ')
excelDf2.head(10) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* In, the first day we learned how to read and write `JSON` Files, with that way you can also import JSON files to `DataFrames`. * Also, you can connect to databases and import your data into `DataFrames` by help of 3rd party libraries. Pandas Fundamentals * This section introduces the new user to the key functionalit... | pd.set_option('max_columns', 12)
pd.set_option('display.notebook_repr_html', True)
marvelDF = pd.read_csv("data/marvel-wikia-data.csv", index_col='page_id')
marvelDF.head(5) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Notice that we specified the `page_id` column as the index, since it appears to be a unique identifier. We could try to create a unique index ourselves by trimming `name`: * First, import the regex module of python.* Then, trim the name column with regex. | import re
pattern = re.compile('([a-zA-Z]|-|\s|\.|\')*([a-zA-Z])')
heroName = []
for name in marvelDF.name:
match = re.search(pattern, name)
if match:
heroName.append(match.group())
else:
heroName.append(name)
heroName | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* This looks okay, let's copy '__marvelDF__' to '__marvelDF_newID__' and assign new indexes. | marvelDF_newID = marvelDF.copy()
marvelDF_newID.index = heroName
marvelDF_newID.head(5) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Let's check the uniqueness of ID's: | marvelDF_newID.index.is_unique | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* So, indices need not be unique. Our choice is not unique because some of superheros have some differenet variations. | pd.Series(marvelDF_newID.index).value_counts() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* The most important consequence of a non-unique index is that indexing by label will return multiple values for some labels: | marvelDF_newID.loc['Peter Parker'] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Let's give a truly unique index by not triming `name` column: | hero_id = marvelDF.name
marvelDF_newID = marvelDF.copy()
marvelDF_newID.index = hero_id
marvelDF_newID.head()
marvelDF_newID.index.is_unique | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can create meaningful indices more easily using a hierarchical index.* For now, we will stick with the numeric IDs as our index for '__NewID__' DataFrame. | marvelDF_newID.index = range(16376)
marvelDF.index = marvelDF['name']
marvelDF_newID.head(5) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Manipulating indices * __Reindexing__ allows users to manipulate the data labels in a DataFrame. * It forces a DataFrame to conform to the new index, and optionally, fill in missing data if requested.* A simple use of `reindex` is reverse the order of the rows: | marvelDF_newID.reindex(marvelDF_newID.index[::-1]).head() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Keep in mind that `reindex` does not work if we pass a non-unique index series. * We can remove rows or columns via the `drop` method: | marvelDF_newID.shape
marvelDF_dropped = marvelDF_newID.drop([16375, 16374])
print(marvelDF_newID.shape)
print(marvelDF_dropped.shape)
marvelDF_dropped = marvelDF_newID.drop(['EYE','HAIR'], axis=1)
print(marvelDF_newID.shape)
print(marvelDF_dropped.shape) | (16376, 12)
(16376, 10)
| Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Indexing and Selection * Indexing works like indexing in NumPy arrays, except we can use the labels in the `Index` object to extract values in addition to arrays of integers. | heroAppearances = marvelDF.APPEARANCES
heroAppearances | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Let's start with Numpy style indexing: | heroAppearances[:3] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Indexing by Label: | heroAppearances[['Spider-Man (Peter Parker)','Hulk (Robert Bruce Banner)']] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can also slice with data labels, since they have an intrinsic order within the Index: | heroAppearances['Spider-Man (Peter Parker)':'Matthew Murdock (Earth-616)'] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* You can change sliced array, and if you get warning it's ok. | heroAppearances['Minister of Castile D\'or (Earth-616)':'Yologarch (Earth-616)'] = 0
heroAppearances | /Users/alpyuzbasioglu/anaconda2/lib/python2.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
"""Entry point for ... | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* In a `DataFrame` we can slice along either or both axes: | marvelDF[['SEX','ALIGN']]
mask = marvelDF.APPEARANCES>50
marvelDF[mask] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* The indexing field `loc` allows us to select subsets of rows and columns in an intuitive way: | marvelDF.loc['Spider-Man (Peter Parker)', ['ID', 'EYE', 'HAIR']]
marvelDF.loc[['Spider-Man (Peter Parker)','Thor (Thor Odinson)'],['ID', 'EYE', 'HAIR']] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Operations * `DataFrame` and `Series` objects allow for several operations to take place either on a single object, or between two or more objects.* For example, we can perform arithmetic on the elements of two objects, such as change in population across years: | populationDF
pop2000 = populationDF['2000']
pop2017 = populationDF['2017']
pop2000DF = pd.Series(pop2000.values, index=populationDF.index)
pop2017DF = pd.Series(pop2017.values, index=populationDF.index)
popDiff = pop2017DF - pop2000DF
popDiff | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Let's assume our '__pop2000DF__' DataFrame has not row which index is "Yalova" | pop2000DF["Yalova"] = np.nan
pop2000DF
popDiff = pop2017DF - pop2000DF
popDiff | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* For accessing not null elements, we can use Pandas'notnull function. | popDiff[popDiff.notnull()] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can add `fill_value` argument to insert a zero for home `NaN` values. | pop2017DF.subtract(pop2000DF, fill_value=0) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can also use functions to each column or row of a `DataFrame` | minPop = pop2017DF.values.min()
indexOfMinPop = pop2017DF.index[pop2017DF.values.argmin()]
print(indexOfMinPop + " -> " + str(minPop))
populationDF['2000'] = np.ceil(populationDF['2000'] / 10000) * 10000
populationDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Sorting and Ranking * Pandas objects include methods for re-ordering data. | populationDF.sort_index(ascending=True).head()
populationDF.sort_index().head()
populationDF.sort_index(axis=1, ascending=False).head() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can also use `order` to sort a `Series` by value, rather than by label. * For a `DataFrame`, we can sort according to the values of one or more columns using the `by` argument of `sort_values`: | populationDF[['2017','2001']].sort_values(by=['2017', '2001'],ascending=[False,True]).head(10) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* __Ranking__ does not re-arrange data, but instead returns an index that ranks each value relative to others in the Series. | populationDF['2010'].rank(ascending=False)
populationDF[['2017','2001']].sort_values(by=['2017', '2001'],ascending=[False,True]).rank(ascending=False) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Ties are assigned the mean value of the tied ranks, which may result in decimal values. | pd.Series([50,60,50]).rank() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Alternatively, you can break ties via one of several methods, such as by the order in which they occur in the dataset: | pd.Series([100,50,100]).rank(method='first') | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Calling the `DataFrame`'s `rank` method results in the ranks of all columns: | populationDF.rank(ascending=False) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Hierarchical indexing * Hierarchical indexing is an important feature of pandas enabling you to have multiple (two or more) index levels on an axis.* Somewhat abstractly, it provides a way for you to work with higher dimensional data in a lower dimensional form. * Let’s create a Series with a list of lists or arrays a... | data = pd.Series(np.random.randn(10),
index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'],
[1, 2, 3, 1, 2, 3, 1, 2, 2, 3]])
data
data.index | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* With a hierarchically-indexed object, so-called partial indexing is possible, enabling you to concisely select subsets of the data: | data['b']
data['a':'c'] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Selection is even possible in some cases from an “inner” level: | data[:, 1] | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Hierarchical indexing plays a critical role in reshaping data and group-based operations like forming a pivot table. For example, this data could be rearranged into a DataFrame using its unstack method: | dataDF = data.unstack()
dataDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* The inverse operation of unstack is stack: | dataDF.stack() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Missing data * The occurence of missing data is so prevalent that it pays to use tools like Pandas, which seamlessly integrates missing data handling so that it can be dealt with easily, and in the manner required by the analysis at hand.* Missing data are represented in `Series` and `DataFrame` objects by the `NaN` f... | weirdSeries = pd.Series([np.nan, None, 'string', 1])
weirdSeries
weirdSeries.isnull() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Missing values may be dropped or indexed out: | population2
population2.dropna()
population2[population2.notnull()]
dataDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* By default, `dropna` drops entire rows in which one or more values are missing. | dataDF.dropna() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* This can be overridden by passing the `how='all'` argument, which only drops a row when every field is a missing value. | dataDF.dropna(how='all') | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* This can be customized further by specifying how many values need to be present before a row is dropped via the `thresh` argument. | dataDF[2]['c'] = np.nan
dataDF
dataDF.dropna(thresh=2) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* If we want to drop missing values column-wise instead of row-wise, we use `axis=1`. | dataDF[1]['d'] = np.random.randn(1)
dataDF
dataDF.dropna(axis=1) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Rather than omitting missing data from an analysis, in some cases it may be suitable to fill the missing value in, either with a default value (such as zero) or a value that is either imputed or carried forward/backward from similar data points. * We can do this programmatically in Pandas with the `fillna` argument. | dataDF
dataDF.fillna(0)
dataDF.fillna({2: 1.5, 3:0.50}) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Notice that `fillna` by default returns a new object with the desired filling behavior, rather than changing the `Series` or `DataFrame` in place. | dataDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* If you don't like this behaviour you can alter values in-place using `inplace=True`. | dataDF.fillna({2: 1.5, 3:0.50}, inplace=True)
dataDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Missing values can also be interpolated, using any one of a variety of methods: | dataDF[2]['c'] = np.nan
dataDF[3]['d'] = np.nan
dataDF | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* We can also propagate non-null values forward or backward. | dataDF.fillna(method='ffill')
dataDF.fillna(dataDF.mean()) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
Data summarization * We often wish to summarize data in `Series` or `DataFrame` objects, so that they can more easily be understood or compared with similar data.* The NumPy package contains several functions that are useful here, but several summarization or reduction methods are built into Pandas data structures. | marvelDF.sum() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Clearly, `sum` is more meaningful for some columns than others.(Total Appearances) * For methods like `mean` for which application to string variables is not just meaningless, but impossible, these columns are automatically exculded: | marvelDF.mean() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* The important difference between NumPy's functions and Pandas' methods is that Numpy have different functions for handling missing data like 'nansum' but Pandas use same functions. | dataDF
dataDF.mean() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* Sometimes we may not want to ignore missing values, and allow the `nan` to propagate. | dataDF.mean(skipna=False) | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* A useful summarization that gives a quick snapshot of multiple statistics for a `Series` or `DataFrame` is `describe`: | dataDF.describe() | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
* `describe` can detect non-numeric data and sometimes yield useful information about it. Writing Data to Files * Pandas can also export data to a variety of storage formats.* We will bring your attention to just a couple of these. | myDF = populationDF['2000']
myDF.to_csv("data/roundedPopulation2000.csv") | _____no_output_____ | Apache-2.0 | iPython Notebooks/Introduction to Pandas Part 1.ipynb | AlpYuzbasioglu/Zeppelin-Notebooks |
S6 Transfer Function Equivalence3C6 Section 6: equivalence of transfer function expressions imports and definitions | import numpy as np
import scipy.linalg as la
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
matplotlib.rcParams.update({'font.size': 12,'font.family':'serif'})
import os
from IPython.display import HTML, display
from ipywidgets import Output, widgets, Layout
%matplotlib noteb... | _____no_output_____ | MIT | S6_transfer_function_equivalance.ipynb | torebutlin/PartIIA-3C6 |
Setup properties | # setup parameters
L = 1
P = 1
m = 1
c = np.sqrt(P/m)
x = 0.6*L
a = 0.2*L
w1 = np.pi*c/L
N = 20
# Create axes
w = np.linspace(0.01,(N+1)*w1,1000)
# Direct approach
if x<a:
G1 = c/(w*P) * np.sin(w*(L-a)/c) * np.sin(w*x/c) / np.sin(w*L/c)
else:
G1 = c/(w*P) * np.sin(w*a/c) * np.sin(w*(L-x)/c) / np.sin(w*L/c)
p... | _____no_output_____ | MIT | S6_transfer_function_equivalance.ipynb | torebutlin/PartIIA-3C6 |
\ Developer: Ali Hashaam (ali.hashaam@initos.com) \ 5th March 2019 \ © 2019 initOS GmbH \ License MIT \ Library for TSVM and SelfLearning taken from https://github.com/tmadl/semisup-learn \ Library for lagrangean-S3VM taken from https://github.com/fbagattini/lagrangean-s3vm | from sklearn.svm import SVC
import pandas as pd
import numpy as np
from __future__ import division
import re
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from frameworks.SelfLearning import *
from imblearn.over_sampling import SM... | 0.845833333333
f1-score precision recall support
0.0 0.841202 0.867257 0.816667 120.0
1.0 0.850202 0.826772 0.875000 120.0
macro avg 0.845702 0.847014 0.845833 240.0
micro avg 0.845833 0.845833 0.845833 240.0
weighted avg 0.845702 0.847014 0.845... | MIT | 9) domain_adaptation/5.domain_adaptation.ipynb | initOS/research-criticality-identification |
Baseline TL Source VS Target Supervised | source_domain_X = tfidf_vectorizer_source.fit_transform(source_domain['text'])
source_domain_Y = np.array(source_domain['type'])
for x in xrange(5):
clf = MultinomialNB()
clf.fit(source_domain_X, source_domain_Y)
target_domain_labeled_balanced = target_domain_labeled.groupby('type').apply(lambda x: x.sample... | members for classes (0.0,90),(1.0,90)
Baseline TL Score: 0.566666666667
members for classes (0,44),(1,136)
0.0 1.0 macro avg micro avg weighted avg
f1-score 0.417910 0.654867 0.536389 0.566667 0.536389
precision 0.636364 0.544118 0.590241 0.566667 0.590241
rec... | MIT | 9) domain_adaptation/5.domain_adaptation.ipynb | initOS/research-criticality-identification |
TL Source Semi-Supervised | target_domain_unlabeled = target_domain.loc[unlabelled_index_target, ["textual_data", "type"]].copy()
target_domain_unlabeled["type"] = -1
source_domain_df = source_domain[["text", "type"]].copy()
source_domain_df.rename({"text":"textual_data", "type":"type"}, axis=1, inplace=1)
domain_adaptation_df = pd.concat([source... | 0.516666666667
members for classes (0.0,90),(1.0,90)
members for classes (0.0,5),(1.0,175)
Confusion matrix, without normalization
[[ 4 86]
[ 1 89]]
| MIT | 9) domain_adaptation/5.domain_adaptation.ipynb | initOS/research-criticality-identification |
1. Connect To Google Drive + Get Data | # MAIN DIRECTORY STILL TO DO
from google.colab import drive
drive.mount('/content/gdrive')
data_file = "/content/gdrive/MyDrive/CSCI4511W/project/sentiments.csv"
import pandas as pd
import numpy as np
cols = ['sentiment','id','date','query_string','user','text']
sms_data = pd.read_csv(data_file, encoding='latin-1',he... | _____no_output_____ | MIT | project_tfif.ipynb | lauraAriasFdez/Ciphers |
Preprocess Data | import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
#We import English stop-words from the NLTK package and removed them if found in the sentence.
#While removing stop-words, we perform stemming that is if the word is not a stop-word, it will be... | [nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data] Unzipping corpora/stopwords.zip.
| MIT | project_tfif.ipynb | lauraAriasFdez/Ciphers |
https://getpocket.com/read/3040941140 Texthero is designed as a Pandas wrapper, so it makes it easier than ever to preprocess and analyze text based Pandas Series | !pip install texthero
import pandas as pd
import texthero as hero #config import cid, csec, ua
custom_cleaning = [
#Replace not assigned values with empty space
hero.preprocessing.fillna,
hero.preprocessing.lowercase,
hero.preprocessing.remove_digits,
hero.preprocessing.remove_punctuation,
hero.preproce... | _____no_output_____ | MIT | project_tfif.ipynb | lauraAriasFdez/Ciphers |
TF-IDF Feature Extraction | from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer()
tfidf_data = tfidf.fit_transform(content)
from sklearn.model_selection import train_test_split
tfidf_x_train,tfidf_x_test,y_train,y_test = train_test_split(tfidf_data,labels,test_size = 0.3, stratify=labels,random_state=100) | _____no_output_____ | MIT | project_tfif.ipynb | lauraAriasFdez/Ciphers |
Multinomial Naive Bayes | from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.metrics import f1_score
# NAIVE BAYES + TLF
print("NAIVE BAYES + TLF______________________________________________________________")
clf_multinomialnb = MultinomialNB()
clf_multinomialnb.fit(... | NAIVE BAYES + TLF______________________________________________________________
precision recall f1-score support
0 0.74 0.79 0.76 240000
1 0.77 0.72 0.75 240000
accuracy 0.76 480000
macro avg 0.7... | MIT | project_tfif.ipynb | lauraAriasFdez/Ciphers |
SVM | from sklearn.svm import LinearSVC
# SVM + TLF
print("LINEAR SVM + TLF______________________________________________________________")
linearsvc = LinearSVC()
linearsvc.fit(tfidf_x_train,y_train)
y_pred = linearsvc.predict(tfidf_x_test)
print(classification_report(y_test,y_pred))
f1_score(y_test,y_pred) | LINEAR SVM + TLF______________________________________________________________
precision recall f1-score support
0 0.78 0.75 0.77 240000
1 0.76 0.79 0.77 240000
accuracy 0.77 480000
macro avg 0.77... | MIT | project_tfif.ipynb | lauraAriasFdez/Ciphers |
Logistic Regression | #https://towardsdatascience.com/logistic-regression-using-python-sklearn-numpy-mnist-handwriting-recognition-matplotlib-a6b31e2b166a
from sklearn.linear_model import LogisticRegression
logisticRegr = LogisticRegression()
logisticRegr.fit(tfidf_x_train,y_train)
y_pred = logisticRegr.predict(tfidf_x_test)
print(classi... | _____no_output_____ | MIT | project_tfif.ipynb | lauraAriasFdez/Ciphers |
Chainer MNIST Model Deployment * Wrap a Chainer MNIST python model for use as a prediction microservice in seldon-core * Run locally on Docker to test * Deploy on seldon-core running on minikube Dependencies * [Helm](https://github.com/kubernetes/helm) * [Minikube](https://github.com/kubernetes/minikube) * [S2I](... | #!/usr/bin/env python
import argparse
import chainer
import chainer.functions as F
import chainer.links as L
import chainerx
from chainer import training
from chainer.training import extensions
# Network definition
class MLP(chainer.Chain):
def __init__(self, n_units, n_out):
super(MLP, self).__init__()
... | /Users/dtaniwaki/.pyenv/versions/3.7.4/lib/python3.7/site-packages/chainer/_environment_check.py:41: UserWarning: Accelerate has been detected as a NumPy backend library.
vecLib, which is a part of Accelerate, is known not to work correctly with Chainer.
We recommend using other BLAS libraries such as OpenBLAS.
For det... | Apache-2.0 | doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb | edshee/seldon-core |
Wrap model using s2i | !s2i build . seldonio/seldon-core-s2i-python37-ubi8:1.7.0-dev chainer-mnist:0.1
!docker run --name "mnist_predictor" -d --rm -p 5000:5000 chainer-mnist:0.1 | b03f58f82ca07e25261be34b75be4a0ffbbfa1ad736d3866790682bf0d8202a3
| Apache-2.0 | doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb | edshee/seldon-core |
Send some random features that conform to the contract | !seldon-core-tester contract.json 0.0.0.0 5000 -p
!docker rm mnist_predictor --force | Error: No such container: mnist_predictor
| Apache-2.0 | doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb | edshee/seldon-core |
Test using Minikube**Due to a [minikube/s2i issue](https://github.com/SeldonIO/seldon-core/issues/253) you will need [s2i >= 1.1.13](https://github.com/openshift/source-to-image/releases/tag/v1.1.13)** | !minikube start --memory 4096 | 😄 minikube v1.2.0 on darwin (amd64)
🔥 Creating virtualbox VM (CPUs=2, Memory=4096MB, Disk=20000MB) ...
🐳 Configuring environment for Kubernetes v1.15.0 on Docker 18.09.6
🚜 Pulling images ...
🚀 Launching Kubernetes ...
⌛ Verifying: apiserver proxy etcd scheduler controller dns
🏄 Done! kubectl is now config... | Apache-2.0 | doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb | edshee/seldon-core |
Setup Seldon CoreUse the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlSetup-Cluster) with [Ambassador Ingress](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.htmlAmbassador) and [Install Seldon Core](https://doc... | !eval $(minikube docker-env) && s2i build . seldonio/seldon-core-s2i-python37-ubi8:1.7.0-dev chainer-mnist:0.1
!kubectl create -f chainer_mnist_deployment.json
!kubectl rollout status deploy/chainer-mnist-deployment-chainer-mnist-predictor-76478b2
!seldon-core-api-tester contract.json `minikube ip` `kubectl get svc amb... | _____no_output_____ | Apache-2.0 | doc/jupyter_execute/examples/models/chainer_mnist/chainer_mnist.ipynb | edshee/seldon-core |
验证集 | val_probability = pd.DataFrame(val_probability)
print(val_probability.shape)
print(val_probability.head())
val_probability.drop(labels=[0],axis=1,inplace=True)
val_probability.to_csv(r'../processed/val_probability_28212.csv',header=None,index=False) | _____no_output_____ | MIT | src/NN_13100+15112.ipynb | VoyagerIII/DigiX-- |
测试集 | import os
model_file = r'../model/model28212_NN_'
csr_testData0 = sparse.load_npz(r'../trainTestData/trainData13100.npz')
csr_testData0.shape
csr_testData1 = sparse.load_npz(r'../trainTestData/trainData15112.npz')
csr_testData1.shape
csr_testData = sparse.hstack((csr_testData0, csr_testData1),format='csr')
del csr_tr... | _____no_output_____ | MIT | src/NN_13100+15112.ipynb | VoyagerIII/DigiX-- |
Make sure you have installed the pygfe package. You can simply call `pip install pygrpfe` in the terminal or call the magic command `!pip install pygrpfe` from within the notebook. If you are using the binder link, then `pygrpfe` is already installed. You can import the package directly. | import pygrpfe as gfe | _____no_output_____ | MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
A simple model of wage and participation\begin{align*}Y^*_{it} & = \alpha_i + \epsilon_{it} \\D_{it} &= 1\big[ u(\alpha_i) \geq c(D_{it-1}) + V_{it} \big] \\Y_{it} &= D_{it} Y^*_{it} \\\end{align*}where we use $$u(\alpha) = \frac{e^{(1-\gamma) \alpha } -1}{1-\gamma}$$and use as initial conditions $D_{i1} = 1\big[ u(\... | def dgp_simulate(ni,nt,gamma=2.0,eps_sd=1.0):
""" simulates according to the model """
alpha = np.random.normal(size=(ni))
eps = np.random.normal(size=(ni,nt))
v = np.random.normal(size=(ni,nt))
# non-censored outcome
W = alpha[:,ax] + eps*eps_sd
# utility
U = (np.exp( al... | _____no_output_____ | MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
Estimating the modelWe show the steps to estimating the model. Later on, we will run a Monte-Carlo Simulation.We simulate from the DGP we have defined. | ni = 1000
nt = 50
Y,D = dgp_simulate(ni,nt,2.0) | _____no_output_____ | MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
Step 1: grouping observationsWe group individuals based on their outcomes. We consider as moments the average value of $Y$ and the average value of $D$. We give our gfe function the $t$ sepcific values so that it can compute the within individual variation. This is a measure used to pick the nubmer of groups.The `grou... | # we create the moments
# this has dimension ni x nt x nm
M_itm = np.stack([Y,D],axis=2)
# we use our sugar function to get the groups
G_i,_ = gfe.group(M_itm)
print("Number of groups = {:d}".format(G_i.max())) | Number of groups = 11
| MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
We can plot the grouping: | dd = pd.DataFrame({'Y':Y.mean(1),'G':G_i,'D':D.mean(1)})
plt.scatter(dd.Y,dd.D,c=dd.G*1.0)
plt.show() | _____no_output_____ | MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
Step 2: Estimate the likelihood model with group specific parametersIn the model we proposed, this second step is a probit. We can then directly use python probit routine with group dummies. | ni,nt = D.shape
# next we minimize using groups as FE
dd = pd.DataFrame({
'd': D[:,range(1,nt)].flatten(),
'dl':D[:,range(nt-1)].flatten(),
'gi':np.broadcast_to(G_i[:,ax], (ni,nt-1)).flatten()})
yv,Xv = patsy.dmatrices("d ~ 0 + dl + C(gi)", dd, return_type='matrix')
mod = Probit(dd['d'], Xv)
res = mod.f... | Optimization terminated successfully.
Current function value: 0.228267
Iterations: 87
Function evaluations: 88
Gradient evaluations: 88
Estimated cost parameters = 0.985
| MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
Step 2 (alternative implementation): Pytorch and auto-diffWe next write down a likelihood that we want to optimize. Instead of using the Python routine for the Probit, we make use of automatic differentiation from PyTorch. This makes it easy to modify the estimating model to accomodate for less standard likelihoods! W... | class GrpProbit:
# initialize parameters and data
def __init__(self,D,G_i):
# define parameters and tell PyTorch to keep track of gradients
self.alpha = torch.tensor( np.ones(G_i.max()+1), requires_grad=True)
self.cost = torch.tensor( np.random.normal(1), requires_grad=True)
se... | Estimated cost parameters = 0.985
| MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
Use PyTorch to estimate Fixed Effect versionSince Pytorch makes use of efficient automatic differentiation, we can use it with many variables. This allows us to give each individual their own group, effectivily estimating a fixed-effect model. | model_fe = GrpProbit(D,np.arange(ni))
gfe.train(model_fe)
print("Estimated cost parameters FE = {:.3f}".format(model_fe.params[1])) | Estimated cost parameters FE = 0.901
| MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
Monte-CarloWe finish with running a short Monte-Carlo exercise. | all = []
import itertools
ll = list(itertools.product(range(50), [10,20,30,40]))
for r, nt in tqdm.tqdm(ll):
ni = 1000
gamma =2.0
Y,D = dgp_simulate(ni,nt,gamma)
M_itm = np.stack([Y,D],axis=2)
G_i,_ = blm2.group(M_itm,scale=True)
model_fe = GrpProbit(D,np.arange(ni))
gfe.train(m... | _____no_output_____ | MIT | docs-src/notebooks/nb-gfe-example1.ipynb | tlamadon/pygfe |
GDP and life expectancyRicher countries can afford to invest more on healthcare, on work and road safety, and other measures that reduce mortality. On the other hand, richer countries may have less healthy lifestyles. Is there any relation between the wealth of a country and the life expectancy of its inhabitants?The ... | import warnings
warnings.simplefilter('ignore', FutureWarning)
import pandas as pd
YEAR = 2018
GDP_INDICATOR = 'NY.GDP.MKTP.CD'
gdpReset = pd.read_csv('WB 2018 GDP.csv')
LIFE_INDICATOR = 'SP.DYN.LE00.IN_'
lifeReset = pd.read_csv('WB 2018 LE.csv')
lifeReset.head() | _____no_output_____ | MIT | Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb | ruthwaiharo/Week-5-Assessment |
Cleaning the dataInspecting the data with `head()` and `tail()` shows that:1. the first 34 rows are aggregated data, for the Arab World, the Caribbean small states, and other country groups used by the World Bank;- GDP and life expectancy values are missing for some countries.The data is therefore cleaned by:1. removi... | gdpCountries = gdpReset.dropna()
lifeCountries = lifeReset.dropna() | _____no_output_____ | MIT | Ugwu Lilian WT-21-138/2018_LE_GDP.ipynb | ruthwaiharo/Week-5-Assessment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.