jekwatt / idiomatic_pandas Goto Github PK
View Code? Open in Web Editor NEWTips and tricks for the most common data handling task with pandas.
Tips and tricks for the most common data handling task with pandas.
normalize column names:
d1 = {c: normalize_name(c) for c in df.columns}
df.rename(columns=d1, inplace=True)
Link I want to check out in depth:
.loc[row_indexer,col_indexer] = value
instead.The proper way to modify df is to apply one of the accessors
.loc[],
.iloc[],
.at[],
or .iat[]
mask = df["A"] > 5
df.loc[mask, 'B'] = 4
Make a deepcopy:
df2 = df[["A"]].copy(deep=True)
Change pd.options.mode.chained_assignment:
pd.set_option("mode.chained_assignment", None)
To find rows with discrepancies:
Method 1: isin function/method
result1 = df1[~df1.apply(tuple, 1).isin(df2.apply(tuple, 1))]
print(result1)
Method 2: merge
# indicator parameter will insert a new field ("_merge")
result2 = df1.merge(df3, indicator=True, how="outer").loc[lambda v: v["_merge"] != "both"]
print(result2)
result3 = df1.merge(df3, indicator=True, how="outer")
result3[test_merge._merge != "both"]
Using Conditionals to Filter Rows and Columns.
Series
df["col_1"]
DataFrame
df[["col_1"]]
Covert Series to DataFrame:
s1.to_dataframe()
Convert DataFrame to Series:
When generating the original data set, there is a call to .squeeze()
which turns a DataFrame with a single column into a Series.
lower, upper, title, and len
e.g.
df["col_1"].str.lower()
df["col_1"].str.upper()
df["col_1"] = df["col_1"].str.title()
df["col_1"].str.len()
To make the change, assign the field to the value:
df["col_1"] = df["col_1"].str.lower()
Add notebook template with basic import and settings for fast start.
These will go under notebooks/03_modifying.
Related code:
http://bit.ly/Pandas-05
There are many ways in combining multiple files with Pandas.
import glob
import os
from pathlib import Path
today = datetime.now().date()
y, m, d = today.year, today.month, today.day
md = f"{m:02d}-{d:02d}"
p = Path.cwd().parents[0]
here = p / 'data' / 'prod' / md
all_csv_files = sorted(glob(os.path.join(here, "*.csv")))
df_from_each_csv = (pd.read_csv(f) for f in all_csv_files)
df = pd.concat(df_from_each_csv, ignore_index=True)
https://pbpython.com/pandas-excel-range.html
With pandas it is easy to read Excel files and convert the data into a DataFrame. Unfortunately Excel files in the real world are often poorly constructed. In those cases where the data is scattered across the worksheet, you may need to customize the way you read the data.
The simplest solution for this data set is to use the header
and usecols
arguments to read_excel().
from pathlib import Path
src_file = Path.cwd() / 'data.xlsx'
df = pd.read_excel(src_file, header=1, usecols='B:F')
# 1
df1 = pd.read_csv('input1.csv')
df1['col_1'] = df1['col_1'].str.strip()
#2
modify your read_csv lines to also use [skipinitialspace=True]
df1 = pd.read_csv('input1.csv', skipinitialspace=True)
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
# 3
pd.read_csv(..., converters={'col_1': str.strip})
# only strip leading whitespace
pd.read_csv(..., converters={'col_1': str.lstrip})
Counting the number of unique values in a pandas DataFrame group involves first splitting the rows into different groups by some criteria, then counting the number of unique values of another column found within each of these groups.
grouped_df = df.groupby("col_1")
grouped_df = grouped_df.agg({"col_2": "nunique"})
Methods to use:
helpers.py
https://datatofish.com/check-nan-pandas-dataframe/
4 ways to check for NaN in Pandas DataFrame:
# check for NaN under a single DataFrame column:
df['col_1'].isnull().values.any()
# count the NaN under a single DataFrame column:
# False -> 0, True -> 1
df['col_1'].isnull().sum()
# check for NaN under an entire DataFrame:
df.isnull().values.any()
# only view missing values
df[df["col_1"].isnull()]
# count the NaN under an entire DataFrame:
df.isnull().sum() # sum of each row
df.isnull().sum().sum()
Answers from Cameron:
Using operator itemgetter:
>>> s = pd.Series([(1,"a"), (2,"b")], name="col1")
>>> df = s.to_frame()
>>>df["col1"].apply(itemgetter(0))
0 1
1 2
Name: col1, dtype: int64
>>>df["col1"].apply(itemgetter(1))
0 a
1 b
Name: col1, dtype: object
That definitely works! You can also use the `.str` accessor to do this too:
>>> s = pd.Series([(1,"a"), (2,"b")])
>>> s.str.get(0)
0 1
1 2
dtype: int64
>>> s.str.get(1)
0 a
1 b
dtype: object
Alternatively, you can explode our these values to work with them in a different way.
>>> s.explode()
0 1
0 a
1 2
1 b
dtype: object
Create notebooks folder and move notebooks into this folder.
Add columns:
df["col_3"] = df["col_1"] + " " + df["col2"]
df[["col_1", "col_2"]] = df["col_3"].str.split(" ", expand=True)
Remove columns:
df.drop(columns=["col_1", "col_2"], inplace=True)
Creating DataFrames from a list of lists with separately defined column names can be especially convenient when dealing with symmetrical data, such as when the number of rows and columns are the same (e.g., 3x3, 4x4, etc.).
This method allows for clear specification of both the column names and the data, enhancing readability and ease of understanding.
import pandas as pd
# Specify column names separately
column_names = ['A', 'B', 'C']
# Data as a list of lists
data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Create DataFrame
df = pd.DataFrame(data, columns=column_names)
print(df)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.