Giter VIP home page Giter VIP logo

idiomatic_pandas's People

Contributors

jekwatt avatar

Watchers

 avatar  avatar

idiomatic_pandas's Issues

Dealing with SettingWithCopyWarning

  1. Try using .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
  1. Make a deepcopy:
    df2 = df[["A"]].copy(deep=True)

  2. Change pd.options.mode.chained_assignment:
    pd.set_option("mode.chained_assignment", None)

Comparing Value Difference Between 2 CSV Files using pandas

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"]

Filtering

Using Conditionals to Filter Rows and Columns.

Series vs. DataFrame

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.

Common string methods

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()

Combining multiple files with Pandas

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)

Reading poorly structured Excel files with Panda

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')

Remove leading/trailing whitespaces

# 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

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"})

groupby

Methods to use:

  • agg
  • transform
  • appy

Handling nulls

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()

Tuple unpacking

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

assign

  • Assign new columns to a DataFrame.
  • Returns a new object with all original columns in addition to new ones.
  • Assigning multiple columns within the same assign is possible.

Add, remove rows and columns from DataFrames

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)

data

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.