Python之DataFrame的使用

以下是Python之DataFrame的使用:

1.定义DataFrame的方式(不带参、使用list、使用列标签)

import pandas as pd
df = pd.DataFrame
print(df)

arr = [1,2,3,4,5]
df = pd.DataFrame(arr)
print(df)

list = [["小明","20"],["小锋","28"]]
df = pd.DataFrame(list,columns=["姓名","年龄"])
print(df)

结果如下

2.定义DataFrame的方式(使用字典+行标签、列表嵌套字典、Series)

import pandas as pd
data = {
    "name": ["小勇","小锋"],
    "age": [28,29],
}
df = pd.DataFrame(data,index=["a","b"])
print(df)

data = [{"name":"小勇","age":28,},{"name":"小民","age":30,}]
df = pd.DataFrame(data)
print(df)

df = pd.DataFrame(pd.Series(["小意","小业"],index=["a","b"]))
print(df)

结果如下

3.获取DataFrame的数据、插入(insert和直接新增字段)和删除(del和pop)字段

import pandas as pd
data = {
    "name": ["小勇","小锋"],
    "age": [28,29],
}
df = pd.DataFrame(data,index=["a","b"])
print(df)
print("--------------")
print(df["age"])
print("--------------")
df.insert(1,column="score",value=[80,100])
print(df)
print("--------------")
del df["score"]
print(df)
print("--------------")
df["score"] = pd.Series([80],index=["b"])
print(df)
print("--------------")
df.pop("score")
print(df)
print("--------------")

结果如下

4.获取某行的数据(loc)

import pandas as pd
data = {
    "name": ["小勇","小锋","小民"],
    "age": [28,29,30],
}
df = pd.DataFrame(data,index=["a","b","c"])
print(df)
print("--------------")
print(df.loc["a"])
print("--------------")
print(df.loc["a":"b"])
print("--------------")

结果如下

5.删除某行的数据(drop)

import pandas as pd
data = {
    "name": ["小勇","小锋","小民"],
    "age": [28,29,30],
}
df = pd.DataFrame(data,index=["a","b","c"])
print(df)
print("--------------")
df = df.drop("b")
print(df)
print("--------------")

结果如下

6.行列转换(T)、获取轴上的字段名(axes)、获取数据类型(dtypes)、清空(empty)

import pandas as pd
data = {
    "name": ["小勇","小锋","小民"],
    "age": [28,29,30],
}
df = pd.DataFrame(data,index=["a","b","c"])
print(df)
print("--------------")

# 行列转换
print(df.T)
print("--------------")

# 获取轴上的字段名
print(df.axes)
print("--------------")

# 获取数据类型
print(df.dtypes)
print("--------------")

# 清空
print(df.empty)
print("--------------")

结果如下

7.获取矩阵形状(shape)、矩阵元素数量(size)、头部和尾部(head和tail)

import pandas as pd
data = {
    "name": ["小勇","小锋","小民"],
    "age": [28,29,30],
}
df = pd.DataFrame(data,index=["a","b","c"])
print(df)
print("--------------")

# 获取矩阵形状
print(df.shape)
print("--------------")

# 获取矩阵元素数量
print(df.size)
print("--------------")

# 获取头部和尾部
print(df.head(2))
print("--------------")
print(df.tail(2))
print("--------------")

结果如下

 

posted @ 2024-01-02 08:59  罗毅豪  阅读(105)  评论(0编辑  收藏  举报