建网站的公司不肯签合同,建立网站的作用,上海最专业的网站设,制作网站网站建设1. 字典的创建方法
1.1 直接创建
# 创建一个包含姓名和年龄的字典
person {name: Alice, age: 25}print(person)
# 输出#xff1a;{name: Alice, age: 25}
1.2 使用 dict() 函数
# 使用键值对列表创建字典
person dict(name…1. 字典的创建方法
1.1 直接创建
# 创建一个包含姓名和年龄的字典
person {name: Alice, age: 25}print(person)
# 输出{name: Alice, age: 25}
1.2 使用 dict() 函数
# 使用键值对列表创建字典
person dict(nameAlice, age25)print(person)
# 输出{name: Alice, age: 25}
1.3 将其他数据类型转换为字典
将列表转换为字典
# 将列表转换为字典索引作为键值作为值
data [apple, banana, cherry]
fruit_dict dict(enumerate(data)) print(fruit_dict)
# 输出{0: apple, 1: banana, 2: cherry}将元组转换为字典
# 将元组转换为字典元组中的第一个元素作为键第二个元素作为值
fruit_tuples [(apple, 1), (banana, 2), (cherry, 3)]
fruit_dict dict(fruit_tuples)print(fruit_dict)
# 输出{apple: 1, banana: 2, cherry: 3} 2. DataFrame的创建方法 2.1 从列表或字典创建
从(二维)列表创建 将列表作为数据传入 pd.DataFrame() 函数并指定列名。
import pandas as pddata [[张三, 18, 90, 85, 95], [李四, 19, 80, 90, 85], [王五, 20, 95, 80, 90]]df pd.DataFrame(data, columns[姓名, 年龄, 语文, 数学, 英语])
print(df)从字典创建 将字典作为数据传入 pd.DataFrame() 函数键作为列名值作为数据。
import pandas as pddata {姓名: [张三, 李四, 王五],年龄: [18, 19, 20],语文: [90, 80, 95],数学: [85, 90, 80],英语: [95, 85, 90]}df pd.DataFrame(data)
print(df)
2.2 其他创建方式:
使用 pd.Series() 创建单列 DataFrame
import pandas as pddata pd.Series([1, 2, 3, 4])
df pd.DataFrame(data, columns[数据])
print(df)#输出
数据
0 1
1 2
2 3
3 4使用 pd.concat() 合并 DataFrame
import pandas as pddf1 pd.DataFrame({A: [1, 2], B: [3, 4]})
df2 pd.DataFrame({A: [5, 6], B: [7, 8]})df pd.concat([df1, df2])
print(df)
输出A B
0 1 3
1 2 4
0 5 7
1 6 8
2.3 从文件创建
df1 pd.read_csv(data.csv) #从csv文件中创建df2 pd.read_excel(data.xls) #从excel文件中创建