

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















ii
Release 1. Date Sep 12, 2022
babypandas is a pandas data-analysis module with a restricted API.
This module is a simplified version of pandas with only methods deemed necessary for an introductory course. babypandas methods also only contain the necessary arguments needed for basic table manipulation and visualiza- tion, reducing the complication found in pandas. Writing this module as a restricted version of pandas allows for an easy transition into pandas.
Contents 1
Summary of DataFrame methods for babyandas. DataFrame are a two-dimensional tabular data structure with labeled rows (indices) and columns.
Click a method to see its documentation.
Creation
DataFrame.init(*kwargs) Create an empty DataFrame. DataFrame.from_dict(data) Construct DataFrame from dict of array-like or dicts. DataFrame.from_records(data, [, columns]) Convert structured or record ndarray to DataFrame. DataFrame.assign(kwargs) Assign new columns to a DataFrame.
DataFrame. init (**kwargs) Create an empty DataFrame.
classmethod DataFrame. from_dict (data) Construct DataFrame from dict of array-like or dicts. Parameters data (dict) – Of the form {field : array-like} or {field : dict}. Returns Return type DataFrame
classmethod DataFrame. from_records (data, *, columns=None) Convert structured or record ndarray to DataFrame. Parameters
DataFrame. assign (kwargs) Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters (^) ****kwargs (dict of {str: callable or Series}) – The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas doesn’t check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned. Returns df_with_cols – A new DataFrame with the new columns in addition to all the existing columns. Return type DataFrame Raises ValueError – If columns have different lengths or if new columns have different lengths than the existing DataFrame
Examples
>>> df = bpd.DataFrame().assign(flower=['sunflower', 'rose']) >>> df.assign(color=['yellow', 'red']) flower color 0 sunflower yellow 1 rose red
Selection
DataFrame.take(indices) Return the rows in the given positional indices. DataFrame.drop(*[, columns]) Remove columns by specifying column names. DataFrame.sample([n, replace, random_state]) Return a random sample of rows from a data frame. DataFrame.get(key) Return column or columns from data frame.
4 Chapter 1. Reference
(continued from previous page) 0 0 3 1 4 7 2 8 11
DataFrame. sample (n=None, *, replace=False, random_state=None) Return a random sample of rows from a data frame. You can use random_state for reproducibility. Parameters
Examples
>>> df = bpd.DataFrame().assign(letter=['a', 'b', 'c'], ... count=[9, 3, 3], ... points=[1, 2, 2]) >>> df.sample(1, random_state=0) letter count points 2 c 3 2
DataFrame. get (key) Return column or columns from data frame. Parameters key (str or iterable of strings) – Column label or iterable of column labels Returns series_or_df – Series with the corresponding label or DataFrame with the corresponding column labels. Return type Series or DataFrame Raises KeyError – If any column named in key not found in columns.
6 Chapter 1. Reference
Examples
>>> df = bpd.DataFrame().assign(letter=['a', 'b', 'c'], ... count=[9, 3, 3], ... points=[1, 2, 2]) >>> df.get('letter') 0 a 1 b 2 c Name: letter, dtype: object >>> df.get(['count', 'points']) count points 0 9 1 1 3 2 2 3 2
Transformation
DataFrame.apply(func[, axis]) Apply a function along an axis of the DataFrame. DataFrame.sort_values(by, [, ascending]) Sort by the values in column(s) named in by. DataFrame.describe() Generate descriptive statistics. DataFrame.groupby(by) Group DataFrame by values in columns specified in by. DataFrame.reset_index([, drop]) Reset the index. DataFrame.set_index(keys[, drop]) Set the DataFrame index using existing columns.
DataFrame. apply (func, axis=0) Apply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1). The final return type is inferred from the return type of the applied function. Parameters
Examples
>>> def add_two(row): ... return row + 2 >>> df = bpd.DataFrame(A=[1, 1], ... B=[2, 2]) >>> df.apply(add_two) A B (continues on next page)
1.1. DataFrame 7
Examples
>>> df = bpd.DataFrame().assign(A=[0, 10, 20], ... B=[1, 2, 3]) >>> df.describe() A B count 3.0 3. mean 10.0 2. std 10.0 1. min 0.0 1. 25% 5.0 1. 50% 10.0 2. 75% 15.0 2. max 20.0 3.
DataFrame. groupby (by) Group DataFrame by values in columns specified in by. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. this can be used to group large amounts of data and compute operations on these groups. Parameters by (label, or list of labels) – Used to determine the groups for the groupby. Should be a label or list of labels that will group by the named columns in self. Notice that a tuple is interpreted a (single) key. Returns df_gb – groupby object that contains information about the groups. Return type DataFrameGroupBy Raises KeyError – If by not found in columns
Examples
>>> df =bpd.DataFrame(animal=['Falcon', 'Falcon', 'Parrot', 'Parrot'], ... max_speed=[380, 370, 24, 26]) >>> df.groupby('animal').mean() max_speed animal Falcon 375. Parrot 25.
DataFrame. reset_index (*, drop=False) Reset the index. Reset the index of the DataFrame, and use the default one instead. Parameters drop (bool, default False, keyword only) – Do not try to insert index into dataframe columns. This resets the index to the default integer index. Returns
1.1. DataFrame 9
Examples
>>> df = bpd.DataFrame().assign(name=['Sally', 'George', 'Bill', 'Ann'], ... age=[21, 25, 18, 28], ... height_cm=[161, 168, 171, 149]) >>> sorted = df.sort_values(by='age') >>> sorted name age height_cm 2 Bill 18 171 0 Sally 21 161 1 George 25 168 3 Ann 28 149 >>> sorted.reset_index(drop= True ) name age height_cm 0 Bill 18 171 1 Sally 21 161 2 George 25 168 3 Ann 28 149
DataFrame. set_index (keys, drop=True) Set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index replaces the existing index. Parameters
Examples
>>> df = bpd.DataFrame().assign(name=['Sally', 'George', 'Bill', 'Ann'], ... age=[21, 25, 18, 28], ... height_cm=[161, 168, 171, 149]) >>> df.set_index('name') age height_cm name (continues on next page)
10 Chapter 1. Reference
Examples
>>> df1 = bpd.DataFrame().assign(pet=['dog', 'cat', 'lizard', 'turtle'], ... kind=['mammal', 'mammal', 'reptile', 'reptile']) >>> df2 = bpd.DataFrame().assign(kind=['mammal', 'reptile', 'amphibian'], ... abr=['m', 'r', 'a']) >>> df1.merge(df2, on='kind') pet kind abr 0 dog mammal m 1 cat mammal m 2 lizard reptile r 3 turtle reptile r
DataFrame. append (other, ignore_index=False) Append rows of other to the end of caller, returning a new object. Columns in other that are not in the caller are added as new columns. Parameters
Plotting
DataFrame.plot(*args, **kwargs) DataFrame plotting accessor and method
DataFrame. plot (*args, **kwargs) DataFrame plotting accessor and method
Examples
>>> df.plot.line() >>> df.plot.scatter('x', 'y') >>> df.plot.hexbin()
12 Chapter 1. Reference
DataFrame.to_csv([path_or_buf, index]) Write object to a comma-separated values (csv) file. DataFrame.to_numpy() Convert the DataFrame to a NumPy array.
DataFrame. to_csv (path_or_buf=None, *, index=True) Write object to a comma-separated values (csv) file. Parameters
DataFrame. to_numpy () Convert the DataFrame to a NumPy array. By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are float16 and float32, the results dtype will be float32. This may require copying data and coercing values, which may be expensive. Parameters None – Returns df_arr – DataFrame as a NumPy array. Return type numpy.ndarray
1.2 Series
Summary of Series methods for babypandas. Series are one-dimensional arrays with labeled indices.
Click a method to see its documentation.
Creation
Series.init(**kwargs) Create an empty Series.
Series. init (**kwargs) Create an empty Series.
Selection
1.2. Series 13
Examples
>>> s = bpd.Series(data=[1, 2, 3, 4, 5]) >>> s.sample(3, random_state=0) 2 3 0 1 1 2 dtype: int >>> s.sample(7, replace= True , random_state=10) 1 2 4 5 0 1 1 2 3 4 4 5 1 2 dtype: int
Transformation
Series.apply(func) Invoke function on values of Series. Series.sort_values([, ascending]) Sort by the values. Series.describe() Generate descriptive statistics. Series.reset_index([, drop]) Reset the index.
Series. apply (func) Invoke function on values of Series. Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values. Parameters func (function) – Python function or NumPy ufunc to apply. Returns a_obj – If func returns a Series object the result will be a DataFrame. Return type Series or DataFrame
Examples
>>> def cut_off_5(val): ... if val > 5: ... return 5 ... else : ... return val >>> s = bpd.Series(data=[1, 3, 5, 7, 9] >>> s.apply(cut_off_5) 0 1 1 3 2 5 3 5 4 5 dtype: int
1.2. Series 15
Series. sort_values (*, ascending=True) Sort by the values. Sort a Series in ascending or descending order. Parameters ascending (bool, default True, keyword only) – If True, sort values in ascending order, otherwise descending. Returns s_series – Series ordered by values. Return type Series
Example
>>> s = bpd.Series(data=[6, 4, 3, 9, 5]) >>> s.sort_values() 2 3 1 4 4 5 0 6 3 9 dtype: int >>> s.sort_values(ascending= False ) 3 9 0 6 4 5 1 4 2 3 dtype: int
Series. describe () Generate descriptive statistics. Statistics summarize the central tendency, dispersion and shape of a Series’ distribution, excluding NaN values. Analyzes both numeric and object series. Parameters None – Returns descr – Summary statistics of the Series provided. Return type Series
Examples
>>> s = bpd.Series(data=[6, 7, 7, 5, 9, 5, 1]) >>> s.describe() count 7. mean 5. std 2. min 1. 25% 5. (continues on next page)
16 Chapter 1. Reference