Pandas Series Flashcards
data = pd.Series((0.25, 0.5, 0.75, 1.0), )
A Pandas Series is a one-dimensional array of indexed data. It can be created from a list or array as follows:
data.values
The values are simply a familiar NumPy array
data.index
The index is an array-like object of type pd.Index
data[1:3]
Like with a NumPy array, data can be accessed by the associated index via the familiar Python square-bracket notation
data = pd.Series([0.25, 0.5, 0.75, 1.0],
index=[‘a’, ‘b’, ‘c’, ‘d’])
data
This explicit index definition gives the Series object additional capabilities. For example, the index need not be an integer, but can consist of values of any desired type. For example, if we wish, we can use strings as an index:
population_dict = {'California': 38332521, 'Texas': 26448193, 'New York': 19651127, 'Florida': 19552860, 'Illinois': 12882135} population = pd.Series(population_dict) population
The Series-as-dictionary analogy can be made even more clear by constructing a Series object directly from a Python dictionary
population[‘California’:’Illinois’]
Unlike a dictionary, though, the Series also supports array-style operations such as slicing:
pd.Series(5.0, index=[100, 200, 300])
data can be a scalar, which is repeated to fill the specified index:
pd.Series({2:’a’, 1:’b’, 3:’c’}, index=[3])
Notice that in this case, the Series is populated only with the explicitly identified keys.
states = pd.DataFrame((population, area), columns=[‘population’, ‘area’])
we can use a dictionary to construct a single two-dimensional object containing this information:
(Matching Indexes)
states.index
Like the Series object, the DataFrame has an index attribute that gives access to the index labels:
states.columns
Additionally, the DataFrame has a columns attribute, which is an Index object holding the column labels:
A DataFrame is a collection of Series objects, and a single-column DataFrame can be constructed from a single Series:
Any list of dictionaries can be made into a DataFrame
Even if some keys in the dictionary are missing, Pandas will fill them in with NaN (i.e., “not a number”) values:
Dataframe
pd.DataFrame({‘population’: population,
‘area’: area})
DataFrame can be constructed from a dictionary of Series objects as well:
pd.DataFrame(np.random.rand(3, 2),
columns=[‘foo’, ‘bar’],
)
Given a two-dimensional array of data, we can create a DataFrame with any specified column and index names. If omitted, an integer index will be used for each: