pandas的基础使用

pandas的基础使用,第1张

快速导入包:

对象创建

Series通过传递值列表来创建 ,让 pandas 创建一个默认整数索引:

s = pd.Series([1, 3, 5, np.nan, 6, 8])
s

 DataFrame通过传递一个 NumPy 数组、一个日期时间索引和标签列来创建一个:

dates = pd.date_range("20220101", periods=6)
dates
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list("ABCD"))
df

 DataFrame通过传递可以转换为类似系列结构的对象字典来创建:

df2 = pd.DataFrame(
{
    "A": 1.0,
    "B": pd.Timestamp("20220101"),
    "C": pd.Series(1, index=list(range(4)), dtype="float32"),
    "D": pd.array([3] * 4, dtype="int32"),
    "E": pd.Categorical(["test", "train", "test", "train"]),
    "F": "foo"
})
df2

结果的列DataFrame具有不同 的dtypes:

 查看数据

以下是查看框架顶部和底部行的方法:

 显示索引,列:

 DataFrame.to_numpy()给出底层数据的 NumPy 表示. 请注意,当您的DataFrame列具有不同的数据类型时,这可能是一项昂贵的 *** 作,这归结为 pandas 和 NumPy 之间的根本区别:NumPy 数组对整个数组有一个 dtype,而 pandas DataFrames 每列有一个 dtype。当您调用 时 DataFrame.to_numpy(),pandas 会找到可以容纳 DataFrame 中所有dtype 的 NumPy dtype。这最终可能是object,这需要将每个值转换为 Python 对象。

对于df,我们DataFrame的所有浮点值, DataFrame.to_numpy()速度很快并且不需要复制数据:

对于df2,DataFrame具有多种 dtype 的 , DataFrame.to_numpy()相对昂贵:

注意:DataFrame.to_numpy()不包括输出的索引或列标签。 

describe()显示数据的快速统计摘要:

 转置您的数据:

 按轴排序:

 按值排序:

 Getting

选择单个列,这会产生 a Series,相当于df.A

 选择 via [],对行进行切片:

 按标签选择

使用标签获取横截面:

 按标签在多轴上选择:

 显示标签切片,包括两个端点

 返回对象的尺寸减小:

 获取标量值:

 为了快速访问标量(相当于先前的方法):

 按位置选择

通过传递的整数的位置进行选择:

 通过整数切片,作用类似于 NumPy/Python:

 通过整数位置位置列表,类似于 NumPy/Python 样式:

 对于显式切片行:

 对于显式切片列:

要明确获取值: 

 为了快速访问标量(相当于先前的方法):

布尔索引

使用单个列的值来选择数据:

 从满足布尔条件的 DataFrame 中选择值:

 使用isin()过滤方法:

df2 = df.copy()
df2["E"] = ["one", "one", "two", "three", "four", "three"]
df2
df2[df2["E"].isin(["two", "four"])]

 Setting

设置新列会自动按索引对齐数据:

s1 = pd.Series([1, 2, 3, 4, 5, 6], index=pd.date_range("20220101", periods=6))
s1
df["F"] = s1
df

 按标签设置值:

df.at[dates[0], "A"] = 0
df

 按位置设置值:

 通过分配一个 NumPy 数组来设置:

df.loc[:, "D"] = np.array([5] * len(df))
df

 where带设置的 *** 作:

df2 = df.copy()
df2[df2 > 0] = -df2
df2

 缺失数据

pandas 主要使用该值np.nan来表示缺失数据。默认情况下,它不包含在计算中。

重新索引允许您更改/添加/删除指定轴上的索引。这将返回数据的副本:

df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ["E"])
df1.loc[dates[0]: dates[1], "E"] = 1
df1

 要删除任何缺少数据的行:

df1.dropna(how="any")

 填充缺失数据:

 要获取值所在的布尔掩码nan

 Stats

*** 作通常排除丢失的数据。

执行描述性统计:

 在另一个轴上进行相同的 *** 作:

 使用具有不同维度且需要对齐的对象进行 *** 作。此外,pandas 会自动沿指定维度进行广播:

s = pd.Series([1, 3, 5, np.nan, 6, 8], index=dates).shift(2)
s

df.sub(s, axis="index")

 Apply

对数据应用函数:

df.apply(np.cumsum)

df.apply(lambda x: x.max() - x.min())

 Histogramming

在直方图和离散化中查看更多信息。

s = pd.Series(np.random.randint(0, 7, size=10))
s
s.value_counts()

字符串方法

Series 在属性中配备了一组字符串处理方法str ,可以方便地对数组的每个元素进行 *** 作,如下面的代码片段所示。请注意,模式匹配str通常默认使用正则表达式(在某些情况下总是使用它们)。

s = pd.Series(["A", "B", "C", "Aaba", "Baca", np.nan, "CABA", "dog", "cat"])
s.str.lower()

 Merge Concat

pandas 提供了各种工具,可以在连接/合并类型 *** 作的情况下,轻松地将 Series 和 DataFrame 对象与索引和关系代数功能的各种集合逻辑组合在一起。

将 pandas 对象与 连接在一起concat():

df = pd.DataFrame(np.random.randn(10, 4))
df

prices = [df[:3], df[3:7], df[7:]]
prices

pd.concat(prices)

 Join

SQL 样式合并。

left = pd.DataFrame({"key": ["foo", "foo"], "lval": [1, 2]})
left

right = pd.DataFrame({"key": ["foo", "foo"], "rval": [4, 5]})
right

pd.merge(left, right, on="key")

 另一个可以举的例子是:

left = pd.DataFrame({"key": ["foo", "bar"], "lval": [1, 2]})
left
right = pd.DataFrame({"key": ["foo", "bar"], "rval": [4, 5]})
right
pd.merge(left, right, on="key")

 Grouping

“分组依据”是指涉及以下一个或多个步骤的过程:

  • 根据某些标准将数据分组

  • 将函数独立应用于每个组

  • 将结果组合成数据结构

df = pd.DataFrame(
{
        "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
        "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
        "C": np.random.randn(8),
        "D": np.random.randn(8),
    })
df

 分组,然后将sum()函数应用于结果组:

df.groupby("A").sum()

 按多列分组形成层次索引,我们可以再次应用该sum()函数:

df.groupby(["A", "B"]).sum()

Reshaping Stack
tuples = list(
    zip(
        *[
            ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
            ["one", "two", "one", "two", "one", "two", "one", "two"],
        ]
    ))
tuples

index = pd.MultiIndex.from_tuples(tuples,names=["first", "second"])
index

df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=["A", "B"])
df

该stack()方法在 DataFrame 的列中“压缩”一个级别:

stacked = df2.stack()
stacked

 对于“堆叠”的 DataFrame 或 Series(将 aMultiIndex作为 ), is index的逆运算,默认情况下会取消堆叠最后一层:stack()unstack()

stacked.unstack()

数据透视表 
df = pd.DataFrame(
    {
        "A": ["one", "one", "two", "three"] * 3,
        "B": ["A", "B", "C"] * 4,
        "C": ["foo", "foo", "foo", "bar", "bar", "bar"] * 2,
        "D": np.random.randn(12),
        "E": np.random.randn(12),
    }
)
df

 我们可以很容易地从这些数据中生成数据透视表:

pd.pivot_table(df, values="D", index=["A", "B"], columns=["C"])

 时间序列

pandas 具有简单、强大、高效的功能,用于在频率转换期间执行重采样 *** 作(例如,将秒数据转换为 5 分钟数据)。

rng = pd.date_range("1/1/2022", periods=20, freq="s")
rng

ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts

ts.resample("5Min").sum()

 时区表示:

rng = pd.date_range("1/1/2022 00:00", periods=5, freq="D")
rng

ts = pd.Series(np.random.randn(len(rng)), rng)
ts

ts_utc = ts.tz_localize("UTC")
ts_utc

 转换到另一个时区:

ts_utc.tz_convert("US/Eastern")

 在时间跨度表示之间转换:

rng = pd.date_range("1/1/2022", periods=5, freq="M")
rng

ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts

ps = ts.to_period()
ps

ps.to_timestamp()

 在句点和时间戳之间进行转换可以使用一些方便的算术函数。在以下示例中,我们将年份以 11 月结束的季度频率转换为季度结束后下个月月底的上午 9 点:

prng = pd.period_range("1990Q1", "2000Q4", freq="Q-NOV")
prng

ts = pd.Series(np.random.randn(len(prng)), prng)
ts

ts.index = (prng.asfreq("M", "e") + 1).asfreq("H", "s") + 9
ts.index

 Categoricals
df = pd.DataFrame(
    {"id": [1, 2, 3, 4, 5, 6], "raw_grade": ["a", "b", "b", "a", "a", "e"]}
)
df

 将原始成绩转换为分类数据类型:

df["grade"] = df["raw_grade"].astype("category")
df["grade"]

 将类别重命名为更有意义的名称(分配 Series.cat.categories()到位!):

df["grade"].cat.categories = ["very good", "good", "very bad"]
df

 重新排序类别并同时添加缺少的类别(默认情况下Series.cat()返回一个新的方法):Series

df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])
df

 排序是按类别中的顺序进行的,而不是词法顺序:

df.sort_values(by="grade")

 按类别列分组也会显示空类别:

df.groupby("grade").size()

 Plotting

我们使用标准约定来引用 matplotlib API:

import matplotlib.pyplot as plt

plt.close("all")

close()方法用于关闭图形窗口:

ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2022", periods=1000))
ts = ts.cumsum()
ts.plot()

 如果在 Jupyter Notebook 下运行,绘图将出现在plot(). 否则使用 matplotlib.pyplot.show显示它或 matplotlib.pyplot.savefig将其写入文件。

plt.show();

在 DataFrame 上,该plot()方法可以方便地绘制带有标签的所有列:

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=["A", "B", "C", "D"])
df

df = df.cumsum()
df

plt.figure()
df.plot()
plt.legend(loc='best')

输入/输出数据 CSV

写入 csv 文件:

df.to_csv("foo.csv")

从 csv 文件中读取:

pd.read_csv("foo.csv")

 HDF5

读取和写入HDFStores。

写入 HDF5 存储:

df.to_hdf("foo.h5", "df")

从 HDF5 存储中读取:

pd.read_hdf("foo.h5", "df")
 Excel

读取和写入MS Excel。

写入excel文件:

df.to_excel("foo.xlsx", sheet_name="sheet1")

从excel文件中读取:

pd.read_excel("foo.xlsx", "sheet1", index_col=None, na_values=["NA"])

 详情链接:10 minutes to pandas — pandas 1.4.2 documentation

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/714115.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存