pandas.read

您所在的位置:网站首页 pandas读取csv文件指定行 pandas.read

pandas.read

2023-09-18 03:16| 来源: 网络整理| 查看: 265

假设数据为:

data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'], 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3], 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']} label = ['a','b','c','d','e','f','g','h','i','j'] df = pd.DataFrame(data,index=label) print(df)

打印结果为:

animal age visits priority a cat 2.5 1 yes b cat 3.0 3 yes c snake 0.5 2 no d dog NaN 3 yes e dog 5.0 2 no f cat 2.0 3 no g snake 4.5 1 no h cat NaN 1 yes i dog 7.0 2 no j dog 3.0 1 no

写入数据:

df.to_csv('animal.csv')

网上有博客介绍的是使用df3.to_csv('animal.csv',index = False)该方法将会造成abcde丢失

读取数据:

df_animal = pd.read_csv('animal.csv',index_col=0) df_animal animal age visits priority No. d dog NaN 3 yes 0 h cat 2.0 1 yes 1 c snake 0.5 2 no 2 f cat 1.5 3 no 3 a cat 2.5 1 yes 4 b cat 3.0 3 yes 5 j dog 3.0 1 no 6 g snake 4.5 1 no 7 e dog 5.0 2 no 8 i dog 7.0 2 no 9

使用index_col=0可以解决。 省略了过程增加序列和排序等步骤,这些不是重点。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3