python按照自定义列写入csv文件

时间:2024-03-14 22:23:35

python按照自定义列写入csv文件

import pandas as pd
#a和b的长度必须保持一致,否则报错
a = [x for x in range(5)]
b = [x for x in range(5,10)]
c = [x for x in range(10,15)]
#字典中的key值即为csv中列名
data = {'speed':a,'ele':b,'flow':c}
dataframe = pd.DataFrame(data)
dataframe.to_csv(r'F:\中国大学Mooc\test.csv')


由于python中的字典是无须的,因此对应的列并不能按照我们输入的进行写入:结果:

python按照自定义列写入csv文件

要是想按照自定义的列写入,可以使用columns,

import pandas as pd
#a和b的长度必须保持一致,否则报错
a = [x for x in range(5)]
b = [x for x in range(5,10)]
c = [x for x in range(10,15)]
#字典中的key值即为csv中列名
data = {'speed':a,'ele':b,'flow':c}
dataframe = pd.DataFrame(data)
dataframe.to_csv(r'F:\中国大学Mooc\test.csv',columns = ['speed','flow','ele'])
#或者
import pandas as pd
#a和b的长度必须保持一致,否则报错
a = [x for x in range(5)]
b = [x for x in range(5,10)]
c = [x for x in range(10,15)]
#字典中的key值即为csv中列名
data = {'speed':a,'ele':b,'flow':c}
dataframe = pd.DataFrame(data,columns = ['speed','flow','ele'])#columns自定义列的索引值
dataframe.to_csv(r'F:\中国大学Mooc\test.csv')



结果:
python按照自定义列写入csv文件

另外可以自定义行的索引值:

import pandas as pd
#a和b的长度必须保持一致,否则报错
a = [x for x in range(5)]
b = [x for x in range(5,10)]
c = [x for x in range(10,15)]
#字典中的key值即为csv中列名
data = {'speed':a,'ele':b,'flow':c}
dataframe = pd.DataFrame(data,index = list('AABBV'))#index指定行的索引值
dataframe.to_csv(r'F:\中国大学Mooc\test.csv',columns = ['speed','flow','ele'])




结果:

python按照自定义列写入csv文件