簡體   English   中英

將列表中的行和列添加到python中的csv

[英]Adding a row and column from a list to a csv in python

我是python的新手,我想對一堆vectors(vectors.csv)運行成對相似性算法。 每個向量代表一個節點。 我有vectors.csv文件,其中包含:

    1,2,3
    4,5,6
    7,8,9

並且我有一個列表,其中y = [56,76,87]描述了這些節點。

我想獲取一個包含以下內容的.csv文件:

    null,56,76,87
    56,1,2,3
    76,4,5,6
    87,7,8,9

在python3中執行此操作的最佳方法是什么?

csv中的矩陣是一個numpy數組。

任何幫助將不勝感激。

提前致謝!

pandas可能會幫助您。

import pandas as pd
y = [56,76,87]
c=pd.read_csv("vector.csv", names=y)
c.index=y

這將為您提供:

    56 76 87
56  1  2  3
76  4  5  6
87  7  8  9

最后導出新生成的數據

c.to_csv('new_file.csv')

定義數組和標簽列表:

In [67]: arr = np.arange(1,10).reshape(3,3)
In [68]: y = [56,76,87]

將標簽列表加入數組:

In [69]: arr1 = np.column_stack((y,arr))

定義標題行:

In [70]: header = 'null,' + ','.join([str(i) for i in y])
In [71]: header
Out[71]: 'null,56,76,87'

savetxt編寫。 注意標題,注釋和fmt參數的使用。 如果需要,可以玩這些游戲:

In [72]: np.savetxt('test.txt', arr1,header=header, fmt='%d',delimiter=',',comments='')
In [73]: cat test.txt
null,56,76,87
56,1,2,3
76,4,5,6
87,7,8,9

savetxt用注釋字符寫標題。 然后遍歷數組數組的行(第一個暗)。 對於每一行,它執行fmt%tuple(row)寫入,其中fmt從您的參數派生。 因此,其核心是格式化行的標准Python文件寫入。

讓我對此有所了解。

“ csv中的矩陣是一個numpy數組。”

不必要。 如果文件是.csv文件,則可以使用csv包並導入數據,如下所示:

import os
import csv

root = r'C:\path\to\my\csv\file'
input_file_name = r'input_data.csv'
output_file_name = r'new_data.csv'

input_path = os.path.join(root, input_file_name)
output_path = os.path.join(root, output_file_name)

導入我們的數據:

with open(input_path, 'r', newline ='') as f:
    csv_reader = csv.reader(f, delimiter=',')
    data = [i for i in csv_reader]
f.close()

然后,您將獲得一個列表列表(就像一個數組,但在Python中是列表數據類型):

[[' 1', '2', '3'], [' 4', '5', '6'], [' 7', '8', '9']]

這是我們的y值,我假設它們是整數:

y = [56,76,87]

我從這里借來了一個有用的函數: 在python中將嵌套列表列表的元素從字符串轉換為整數

def int_conversion(my_list):
    return [int(x) if not isinstance(x, list) else int_conversion(x) for x in my_list]

我們的函數進行了一些數據類型轉換,但是輸出整數值:

def process_data(my_data=data):
    # copy the raw data list
    new_data = my_data

    # Convert our y values to stings for processing
    y_1 = [str(i) for i in y]

    # Insert each value of our y list at the first spot in each sublist
    for i in range(len(my_data)):
        new_data[i].insert(0, y_1[i])

    # Insert a '0' placeholder at the start of our y list
    y_1.insert(0, '0')

    # Insert the y list as a sublist in our main data list
    new_data.insert(0, y_1)

    # Convert the list values to integers
    new_data = int_conversion(new_data)

    # Replace the first value in the first sublist with a null (None) value
    new_data[0][0] = None

    # Return the results
    return new_data

處理然后寫輸出:

data = process_data()

with open(output_path, mode='w', newline='') as xyz:
    writer = csv.writer(xyz)
    writer.writerows(data)

然后,您的文件應如下所示:

,56,76,87
56,1,2,3
76,4,5,6
87,7,8,9

由於從概念上講,第一行和第一列表示標簽 ,因此您不妨考慮以NumPy數組對象為基礎的Pandas:

import pandas as pd
from io import StringIO

x = """1,2,3
4,5,6
7,8,9"""

# read data; replace StringIO(x) with 'file.csv'
df = pd.read_csv(StringIO(x), header=None)

# define column and index properties
idx = [56,76,87]
df.columns = idx
df.index = idx

# export to csv
df.to_csv('out.csv')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM