Python implements multiple lists stored as CSV or excel

Features:

Multiple lists can be merged and stored as csv or excel, and can be stored in rows and columns!

There is not much bb directly on the code, it has been encapsulated into a function, and you can call it directly!

Suppose our data consists of multiple lists, which is more common in real-world situations

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7, 8, 9]

When calling this function, we need to encapsulate these lists into a dictionary: the key in the dictionary is the column name that the expected list is expected to display in csv/excel, and the value is the list that needs to be stored

Data = {'one':list1, 'two':list2, 'three':list3}

Function calls (stored by column):

Save_to_Csv(data = Data, file_name = 'demo', Save_format = 'csv',Save_type = 'col')

display effect:

Function calls (stored by row):

Save_to_Csv(data = Data, file_name = 'demo', Save_format = 'csv',Save_type = 'row')

display effect:

Code:

def Save_to_Csv(data, file_name, Save_format = 'csv', Save_type = 'col'):
    # data
    # 输入为一个字典,格式: { '列名称': 数据,....} 
    # 列名即为CSV中数据对应的列名, 数据为一个列表
    
    # file_name 存储文件的名字
    # Save_format 为存储类型, 默认csv格式, 可改为 excel
    # Save_type 存储类型 默认按列存储, 否则按行存储
    
    # 默认存储在当前路径下
    
    import pandas as pd
    import numpy as np
    
    Name = []
    times = 0

    if Save_type == 'col':
        for name, List in data.items():
            Name.append(name)
            if times == 0:
                Data = np.array(List).reshape(-1,1)
            else:
                Data = np.hstack((Data, np.array(List).reshape(-1,1)))
                
            times += 1
            
        Pd_data = pd.DataFrame(columns=Name, data=Data) 
        
    else:
        for name, List in data.items():
            Name.append(name)
            if times == 0:
                Data = np.array(List)
            else:
                Data = np.vstack((Data, np.array(List)))
        
            times += 1
    
        Pd_data = pd.DataFrame(index=Name, data=Data)  
    
    if Save_format == 'csv':
        Pd_data.to_csv('./'+ file_name +'.csv',encoding='utf-8')
    else:
        Pd_data.to_excel('./'+ file_name +'.xls',encoding='utf-8')

 

 

 

 

Guess you like

Origin blog.csdn.net/jac_chao/article/details/115159468