首页 技术 正文
技术 2022年11月15日
0 收藏 533 点赞 4,692 浏览 1411 个字

这一节想总结一下 生成 Dataframe 的几种方式:

  1. CSV
  2. Excel
  3. python dictionary
  4. List of tuples
  5. List of dictionary

下面分别一一介绍具体的实现方式:

  • 通过 csv 文件
    这里补充一个知识点, 就是如果要读取的文件不在 jupyter 所在的文件夹, 则可以通过绝对路径的方式引入.
df = pd.read_csv("/Users/rachel/Downloads/weather.csv")
  • 通过 Excel 文件
    这里的第二个参数是必填项, 因为要指明具体读取 excel 表中的哪个 sheet.
df = pd.read_excel("/Users/rachel/Downloads/weather.xlsx", "weather")

还有一个小坑, 就是在初次运行的时候有可能会提示错误, 根据错误提示, 大概可以了解到, 要读取 excel 文件, 还需要一个 xlrd 的包, 在终端运行下面命令就好了

pip3 install xlrd
  • 通过 python dictionary (为了方便大家日后可以更好地理解英文文档, 这里的一些专业名词, 我就都不翻译了)
weather_data = {
'day': ['1/1/2017','1/2/2017','1/3/2017'],
'temperature': [32,35,28],
'windspeed': [6,7,2],
'event': ['Rain', 'Sunny', 'Snow']
}
df = pd.DataFrame(weather_data)
  • 通过 List of tuples
weather_data = [
('1/1/2017',32,6,'Rain'),
('1/2/2017',35,7,'Sunny'),
('1/3/2017',28,2,'Snow')
]
df = pd.DataFrame(data=weather_data, columns=['day','temperature','windspeed','event'])

上面例子中, weather_data 的数据结构是一个 list(特点是中括号), list 中的每一个元素就是一个 tuple, 由于原数据没有指明列名, 所以在创建 dataframe 的时候, 需要指明列名.

  • 通过 List of dictionary, 从名字就可以读出来下面的数据结构是一个 list, list 中的每个元素又是一个 dictionary.
weather_data = [
{'day': '1/1/2017', 'temperature': 32, 'windspeed': 6, 'event': 'Rain'},
{'day': '1/2/2017', 'temperature': 35, 'windspeed': 7, 'event': 'Sunny'},
{'day': '1/3/2017', 'temperature': 28, 'windspeed': 2, 'event': 'Snow'},]
df = pd.DataFrame(data=weather_data, columns=['day','temperature','windspeed','event'])

上面简要介绍了 5 中生成 dataframe 的方式, 其实 Pandas 还支持很多种文件格式的输入输出, 具体可以参考下官方文档 https://pandas.pydata.org/pandas-docs/version/0.22/io.html

有任何问题或意见, 欢迎留言交流哦~~~

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,498
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,136
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,300