微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pandas 基础(3) - 生成 Dataframe 的几种方式

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

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐