【pd】pandas数据结构

pandas基本数据结构

  • Series(序列):一种一维的带标签数组,可以存储任何类型的数据,例如整数、字符串、Python 对象等。

  • DataFrame(数据框):一种二维的数据结构,类似于二维数组或带有行和列的表格,用于存储结构化数据。

创建

  • 通过传入一个值列表list来创建一个 Series,此时由 pandas 自动创建默认的 RangeIndex(范围索引)。
s1 = pd.Series([5,6,7,np.nan,9])

"""
s1:
0    5.0
1    6.0
2    7.0
3    NaN
4    9.0
dtype: float64
"""
  • 通过传入参数data|index|columns来创建DataFrame
df = pd.DataFrame(np.random.randn(4,3),index=list("ABCD"),\
                    columns=list("MNK"))
df

"""
	M		N		K
A	1.695628	-0.339334	0.760797
B	1.126433	-1.124498	-0.514690
C	-0.269324	1.917150	-1.320400
D	-0.465340	0.052074	-0.454910

"""
  • 通过传入对象字典创建 DataFrame
  1. 字典中的作为列标签(columns)
  2. 键对应的作为该列的数据内容
df2 = pd.DataFrame(
    {
        "A": 1.0,
        "B": pd.Timestamp("20130102"),
        "C": pd.Series(1, index=list(range(4)), dtype="float32"),
        "D": np.array([3] * 4, dtype="int32"),
        "E": pd.Categorical(["test1", "train1", "test2", "train2"]),
        "F": "aaa",
    }
)

"""
	A		B	C	D	E	F
0	1.0	2013-01-02	1.0	3	test1	aaa
1	1.0	2013-01-02	1.0	3	train1	aaa
2	1.0	2013-01-02	1.0	3	test2	aaa
3	1.0	2013-01-02	1.0	3	train2	aaa

"""
posted @ 2025-05-15 09:55  wasline  阅读(17)  评论(0)    收藏  举报