Skip to content

Instantly share code, notes, and snippets.

@hepplerj
Created May 23, 2018 14:45
Show Gist options
  • Save hepplerj/88dab83554701faa3360f586175ec8cd to your computer and use it in GitHub Desktop.
Save hepplerj/88dab83554701faa3360f586175ec8cd to your computer and use it in GitHub Desktop.
An evolving set of pandas snippets I find useful
# Unique values in a dataframe column
df['column_name'].unique()
# Grab dataframe rows where column = value
df = df.loc[df.column == 'some_value']
# Grab dataframe rows where column value is present in a list
value_list = ['value1', 'value2', 'value3']
df = df.loc[:,df.columns.isin(valuelist)]
# or grab rows where a value is not present in a list
df = df.loc[:,~df.columns.isin(valuelist)]
# Delete column from dataframe
del df['column_name']
# Lower-case all dataframe column names
df.columns = map(str.lower, df.columns)
# Lower-case everything in a dataframe column
df.column_name = df.column_name.str.lower()
# Get the length of data in a dataframe column
df.column_name.str.len()
# Get a quick count of rows in the dataframe
len(df.index)
# Concatenate two dataframe columns into a new column
df['new_column'] = df['column1'].astype(str) + df['column2'].astype(str)
# Create a dataframe from a Python dictionary
df = pd.DataFrame(list(a_dictionary.items()), columsn = ['column1', 'column2']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment