python中pandas常用命令实例分析

发布时间:2022-07-28 10:37:38 作者:iii
来源:亿速云 阅读:124

这篇文章主要介绍“python中pandas常用命令实例分析”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“python中pandas常用命令实例分析”文章能帮助大家解决问题。

pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。

1、pandas

pandas 是一个多功能且功能强大的数据科学库。 

2、读取数据

pd.read_csv("data.csv")

3、读取指定列

pd.read_csv("data.csv", usecols=["date", "price"])

4、读取并解析日期

pd.read_csv("data.csv", parse_dates=["date"])

5、读取时指定数据类型

        在读取时设置类别数据类型可以节省内存。

pd.read_csv("data.csv", dtype={"house_type": "category"})

6、读取时设置索引

pd.read_csv("data.csv", index_col="date")

7、设置读取的行数

pd.read_csv("data.csv", nrows=100)

8、读取时跳过行数

pd.read_csv("data.csv", skiprows=[1, 5])  # skips line 1 and 5
pd.read_csv("data.csv", skiprows=100)  # skips the first 100 lines
pd.read_csv("data.csv", skiprows=lambda x: x > 0 and np.random.rand() > 0.1) # skip 90% of the rows

9、指定NA值

pd.read_csv("data.csv", na_values=["?"])

10、设置布尔值

pd.read_csv("data.csv", true_values=["yes"], false_values=["no"])

11、一次读取多个文件后合并

import glob
import os
files = glob.glob("file_*.csv")
result = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)

12、复制数据

df = pd.read_clipboard()

13、从 PDF 文件中读取表格

from tabula import read_pdf
# Read pdf into list of DataFrame
df = read_pdf('test.pdf', pages='all')

14、快速可视化数据集

import pandas_profiling
df = pd.read_csv("data.csv")
profile = df.profile_report(title="Pandas Profiling Report")
profile.to_file(output_file="output.html")

15、按dtype过滤列

# 选择
df.select_dtypes(include="number")
df.select_dtypes(include=["category", "datetime"])
 
# 排除
df.select_dtypes(exclude="object")

16、推断数据类型

df.infer_objects().dtypes

17、向下转换数值类型

pd.to_numeric(df.numeric_col, downcast="integer") # smallest signed int dtype
pd.to_numeric(df.numeric_col, downcast="float")  # smallest float dtype

18、防止错误值并填充

# apply to whole data frame
df = df.apply(pd.to_numeric, errors="coerce")
# apply to specific columns
pd.to_numeric(df.numeric_column, errors="coerce")
# filling NA values with zero
pd.to_numeric(df.numeric_column, errors="coerce").fillna(0)

19、按列数据类型转换

df = df.astype(
    {
        "date": "datetime64[ns]",
        "price": "int",
        "is_weekend": "bool",
        "status": "category",
    }
)

20、重命名列

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

21、添加后缀和前缀

df.add_prefix("pre_")
df.add_suffix("_suf")

22、从原列创建新列

# create new column of Fahrenheit values from Celcius
df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)

23、在特定位置插入列

random_col = np.random.randint(10, size=len(df))
df.insert(3, 'random_col', random_col) # inserts at third column

24、三元表达式

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

25、删除列

df.drop('col1', axis=1, inplace=True)
df = df.drop(['col1','col2'], axis=1)
s = df.pop('col')
del df['col']
df.drop(df.columns[0], inplace=True)

26、修改列名

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

27、判断包含

df['name'].str.contains("John")
df['phone_num'].str.contains('...-...-....', regex=True)  # regex
df['email'].str.contains('gmail')

28、根据正则查找

pattern = '([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\\.([A-Z]{2,4})'
df['email'].str.findall(pattern, flags=re.IGNORECASE)

29、检查缺失值并打印缺失百分比

def missing_vals(df):
    """prints out columns with perc of missing values"""
    missing = [
        (df.columns[idx], perc)
        for idx, perc in enumerate(df.isna().mean() * 100)
        if perc > 0
    ]
 
    if len(missing) == 0:
        return "no missing values"
    
    # sort desc by perc
    missing.sort(key=lambda x: x[1], reverse=True)
 
    print(f"There are a total of {len(missing)} variables with missing values\n")
 
    for tup in missing:
        print(str.ljust(f"{tup[0]:<20} => {round(tup[1], 3)}%", 1))
missing_vals(df)

30、处理缺失值

# drop 
df.dropna(axis=0)
df.dropna(axis=1)
# impute
df.fillna(0)
df.fillna(method="ffill")
df.fillna(method='bfill')
# replace
df.replace( -999, np.nan)
df.replace("?", np.nan)
# interpolate
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")

31、从今天/之前获取 X 小时/天/周

# from today
date.today() + datetime.timedelta(hours=30)
date.today() + datetime.timedelta(days=30)
date.today() + datetime.timedelta(weeks=30)
 
# ago
date.today() - datetime.timedelta(days=365)

32、过滤两个日期

df[(df["Date"] > "2015-01-01") & (df["Date"] < "2017-01-01")]

33、按日/月/年过滤

df[(df["Date"] > "2015-01-01") & (df["Date"] < "2017-01-01")]

34、格式化数据格式

format_dict = {
    "Date": "{:%d/%m/%y}",
    "Open": "${:.2f}",
    "Close": "${:.2f}",
    "Volume": "{:,}",
}
 
df.style.format(format_dict)

35、设置数据颜色

(
    df.style.format(format_dict)
    .hide_index()
    .highlight_min(["Open"], color="red")
    .highlight_max(["Open"], color="green")
    .background_gradient(subset="Close", cmap="Greens")
    .bar('Volume', color='lightblue', align='zero')
    .set_caption('Tesla Stock Prices in 2017')
)

36、获取一列中最大最小项的id

df['col'].idxmin()
df['col'].idxmax()

37、对数据列应用函数

df.applymap(lambda x: np.log(x))

38、随机打乱数据

df.sample(frac=1, random_state=7).reset_index(drop=True)

39、时间序列的百分比变化

df['col_name'].pct_change()

40、分配等级

df['rank'] = df['column_to_rank'].rank()

41、检查内存占用

df.memory_usage().sum() / (1024**2) #converting to MB

42、将列的值分解为多行

df.explode("col_name").reset_index(drop=True)

43、将数量较小的类别转换为“其他”

subclass = df.MSSubClass
subclass.value_counts()
top_five = subclass.value_counts().nlargest(5).index
mssubclass_new = subclass.where(subclass.isin(top_five), other="Other")
mssubclass_new.value_counts()

关于“python中pandas常用命令实例分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

推荐阅读:
  1. Python中pandas如何安装
  2. Python中pandas是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python pandas

上一篇:怎么用java代码P图

下一篇:Golang中的包及包管理工具go mod怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》