当前位置:首页 >> 中医美容 >> 体会30个超级好用的Pandas实战技巧

体会30个超级好用的Pandas实战技巧

发布时间:2023-03-05

pandas_profiling

df = pd.read_csv("data.csv")

profile = df.profile_report(title="Pandas Profiling Report")

profile.to_file(output_file="output.html")

基于统计模板的操作方法 pandas能够表示的统计模板有很多

基于统计模板来挑选统计数据 我们愿意挑选显现出来的统计数据包含或者是不包含我们一切都是的统计模板的统计数据,codice_如下

# 挑选统计数据

df.select_dtypes(include="number")

df.select_dtypes(include=["category", "datetime"])

# 也就是说统计数据

df.select_dtypes(exclude="object")

推断统计模板 主要函数调用的是infer_objects()作法,codice_如下

df.infer_objects().dtypes

手动同步进不依统计模板的反转 我们手动地同步进不依统计模板的反转,要是碰上无法反转的原因时,errors='coerce'将其换转成NaN,codice_如下

# 针对整个统计数据集都直接

df = df.apply(pd.to_numeric, errors="coerce")

# 将空值用零来填入

pd.to_numeric(df.numeric_column, errors="coerce").fillna(0)

一次性未完成统计模板的反转 中用的是astype作法,codice_如下

df = df.astype(

{

"date": "datetime64[ns]",

"price": "int",

"is_weekend": "bool",

"status": "category",

}

特的操作方法 重命名 rename()作法同步进不依特的重命名,codice_如下

df = df.rename({"PRICE": "price", "Date (mm/dd/yyyy)": "date", "STATUS": "status"}, axis=1)

添加词组或者是后缀 add_prefix()作法以及add_suffix()作法,codice_如下

df.add_prefix("pre_")

df.add_suffix("_suf")

新建一个特 函数调用的是assign作法,当然除此之外还有其他的作法可可让尝试,codice_如下

# 摄氏度与华氏度之间的数制反转

df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)

在而无须的位置填入新的一特 同样也是中用insert作法,codice_如下

random_col = np.random.randint(10, size=len(df))

df.insert(3, 'random_col', random_col) # 在第三特的以外填入

if-else逻辑确实

df["price_high_low"] = np.where(df["price"]> 5, "high", "low")

去掉某些特 函数调用的是drop()作法,codice_如下

df.drop('col1', axis=1, inplace=True)

df = df.drop(['col1','col2'], axis=1)

df.drop(df.columns[0], inplace=True)

codice_的操作方法 特于的操作方法 要是我们一切都是对特于做显现出一些改变,codice_如下

# 对于特于的codice_操作方法

df.columns = df.columns.str.lower()

df.columns = df.columns.str.replace(' ', '_')

Contains()作法

## 是否包含了某些codice_

df['name'].str.contains("John")

## 之中可以摆放在正则表达式

df['phone_num'].str.contains('...-...-....', regex=True) # regex

findall()作法

## 正则表达式

pattern = '([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{1,9})'

df['email'].str.findall(pattern, flags=re.IGNORECASE)

缺失值 查看空值的比率 我们要是一切都是查看在统计数据集当中空值所占去的比率,codice_如下

def missing_vals(df):

"""空值所占去的百分比"""

missing = [

(df.columns[idx], perc)

for idx, perc in enumerate(df.isna().mean() * 100)

if perc> 0

]

if len(missing) == 0:

return "没有空值统计数据的普遍存在"

# 排序

missing.sort(key=lambda x: x[1], reverse=True)

print(f"总共有 {len(missing)} 个变数普遍存在空值")

for tup in missing:

print(str.ljust(f"{tup[0]: {round(tup[1], 3)}%", 1))

output

总共有 19 个变数普遍存在空值

PoolQC => 99.521%

MiscFeature => 96.301%

Alley => 93.767%

Fence => 80.753%

FireplaceQu => 47.26%

LotFrontage => 17.74%

GarageType => 5.548%

GarageYrBlt => 5.548%

GarageFinish => 5.548%

GarageQual => 5.548%

GarageCond => 5.548%

BsmtExposure => 2.603%

BsmtFinType2 => 2.603%

BsmtQual => 2.534%

BsmtCond => 2.534%

BsmtFinType1 => 2.534%

MasVnrType => 0.548%

MasVnrArea => 0.548%

Electrical => 0.068%

空值的处理方式 我们可以选择将空值去除掉,或者用平均值或者其他误差来同步进不依填入,codice_如下

# 去除掉空值

df.dropna(axis=0)

df.dropna(axis=1)

# 换成其他值来填入

df.fillna(0)

df.fillna(method="ffill")

df.fillna(method='bfill')

# 取代为其他的误差

df.replace( -999, np.nan)

df.replace("?", np.nan)

# 推测其空值应该为其他什么误差

ts.interpolate() # time series

df.interpolate() # fill all consecutive values forward

df.interpolate(limit=1) # fill one consecutive value forward

df.interpolate(limit=1, limit_direction="backward")

df.interpolate(limit_direction="both")

年份格式的统计数据处理 获取而无须一段时间的统计数据

# 从今天开始算,之后的N天或者N个礼拜或者N个小时

date.today() + datetime.timedelta(hours=30)

date.today() + datetime.timedelta(days=30)

date.today() + datetime.timedelta(weeks=30)

# 依然的一年

date.today() - datetime.timedelta(days=365)

通过年份一段时间来获取统计数据

df[(df["Date"]> "2015-10-01") Wild (df["Date"] 通过而无须年份来获取统计数据

# 挑选显现出某一天的统计数据

df[df["Date"].dt.strftime("%Y-%m-%d") == "2022-03-05"]

# 挑选显现出某一个月的统计数据

df[df["Date"].dt.strftime("%m") == "12"]

# 挑选显现出都是在的统计数据

df[df["Date"].dt.strftime("%Y") == "2020"]

将格式化统计数据集 保有而无须以此类推 对于一些整数的统计数据,我们愿意可以保有小数点后的两位或者是三位,codice_如下

format_dict = {

"Open": "${:.2f}",

"Close": "${:.2f}",

"Volume": "{:,}",

}

df.style.format(format_dict)

output

高亮显示统计数据 对于而无须的一些统计数据,我们愿意是高亮显示,codice_如下

df.style.format(format_dict)

.hide_index()

.highlight_min(["Open"], color="blue")

.highlight_max(["Open"], color="red")

.background_gradient(subset="Close", cmap="Greens")

.bar('Volume', color='lightblue', align='zero')

.set_caption('Tesla Stock Prices in 2017')

output

增强免疫力可以吃什么维生素
宁波看白癜风去哪里最好
南京看白癜风哪家医院专业
江苏男科医院挂号
驻马店看白癜风去哪家好
标签:
友情链接: