Docsity

Release 1.0, Exams of Computer Networks

Partial preview of the text

Download Release 1.0 and more Exams Computer Networks in PDF only on Docsity!

BabyPandas

Release 1.

Sep 12, 2022

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

CHAPTER 1

Reference

1.1 DataFrame

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.

1.1.1 bpd.DataFrame.init

DataFrame. init (**kwargs) Create an empty DataFrame.

1.1.2 bpd.DataFrame.from_dict

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

1.1.3 bpd.DataFrame.from_records

classmethod DataFrame. from_records (data, *, columns=None) Convert structured or record ndarray to DataFrame. Parameters

  • data (ndarray (structured dtype), list of tuples, dict, or DataFrame) –
  • columns (sequence, default None, keyword-only) – Column names to use. If the passed data do not have names associated with them, this argument provides names for the columns. Otherwise this argument indicates the order of the columns in the result (any names not found in the data will become all-NA columns) Returns Return type DataFrame

1.1.4 bpd.DataFrame.assign

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

1.1.7 bpd.DataFrame.sample

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

  • n (None or int, optional) – Number of rows to return. None corresponds to 1.
  • replace ({False, True}, optional, keyword only.) – Sample with or without replacement.
  • random_state (int or numpy.random.RandomState, optional, keyword only) – Seed for the random number generator (if int), or numpy Ran- domState object. Returns s_df – A new DataFrame containing n items randomly sampled from the caller object. Return type DataFrame Raises ValueError – If a sample larger than the length of the DataFrame is taken without re- placement.

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

1.1.8 bpd.DataFrame.get

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.

1.1.9 bpd.DataFrame.apply

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

  • func (function) – Function to apply to each column or row.
  • axis ({0 or 'index', 1 or 'columns'}, default 0) – Axis along which the function is applied:
    • 0 or ‘index’: apply function to each column.
    • 1 or ‘columns’: apply function to each row. Returns applied – Result of applying func along the given axis of the DataFrame. Return type Series or DataFrame

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.

1.1.12 bpd.DataFrame.groupby

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.

1.1.13 bpd.DataFrame.reset_index

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

  • DataFrame – DataFrame with the new index.

1.1. DataFrame 9

  • Reset the index of the DataFrame, and use the default one
  • instead. If the DataFrame has a MultiIndex, this method can
  • remove one or more levels.

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

1.1.14 bpd.DataFrame.set_index

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

  • keys (label or array-like or list of labels/arrays) – This parame- ter can be either a single column key, a single array of the same length as the calling DataFrame, or a list containing an arbitrary combination of column keys and arrays. Here, “array” encompasses Series, Index and np.ndarray.
  • drop (bool, default True) – Delete columns to be used as the new index. Returns Data frame with changed row labels. Return type DataFrame Raises KeyError – If keys not found in columns.

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

  • right_index (boolean, default False) – Use the index from the right DataFrame as the join key. Same caveats as left_index DataFrame. These arrays are treated as if they are columns. Returns A DataFrame of the two merged objects. Return type DataFrame Raises KeyError – If any input labels are not found in the corresponding DataFrame’s columns.

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

1.1.16 bpd.DataFrame.append

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

  • other (DataFrame or Series/dict-like object, or list of these)
    • The data to append.
  • ignore_index (boolean, default False) – If True, do not use the index labels. Returns a_df – DataFrame with appended rows. Return type DataFrame

Plotting

DataFrame.plot(*args, **kwargs) DataFrame plotting accessor and method

1.1.17 bpd.DataFrame.plot

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

IO

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.

1.1.18 bpd.DataFrame.to_csv

DataFrame. to_csv (path_or_buf=None, *, index=True) Write object to a comma-separated values (csv) file. Parameters

  • path_or_buf (str or file handle, default None) – File path or object, if None is provided the result is returned as a string.
  • index (bool, default True) – Write row names (index). Returns If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None. Return type None or str

1.1.19 bpd.DataFrame.to_numpy

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.

1.2.1 bpd.Series.init

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.

1.2.4 bpd.Series.apply

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

1.2.5 bpd.Series.sort_values

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

1.2.6 bpd.Series.describe

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