簡體   English   中英

將數據作為每行的列附加到文件中 (Python)

[英]Appending data to file as columns for each row (Python)

我為數據文件執行了一組計算,並希望將這些新信息附加回。如果原始文件是 [nxm] 並且我有 [nx 6] 的新數據,那么最簡單的方法是什么附加數據的方法? 例如,如果您有:

`    Data = [(0 1 2),
         (3 4 5)]
new_data = [(1 1 1 0 0 0),
            (0 1 0 1 0 1)]
desired_result = [(0 1 2 1 1 1 0 0 0), 
                  (3 4 5 0 1 0 1 0 1)]`

這如何在 Python 中實現? 我在看 Pandas,但我對編程還很陌生,還沒有弄清楚。 最后,我希望將我的原始“數據”文件作為所需的結果,並且我正在努力解決如何將 new_data 正確傳遞到原始文件的部分。

由於您在這里擁有的是一個元組列表,因此您可以像這樣從每個列表中獲取元組:

Data = [(0, 1, 2),(3, 4, 5)]
new_data = [(1, 1, 1, 0, 0, 0), (0, 1, 0, 1, 0, 1)]

# Im assmuming this is how you meant to format the data, please comment if I'm wrong, as I can't leave a comment on your post

expected_result = []

for i in range(len(Data)):
    # Add tuples from each list and append result to a new list
    expected_result.append(Data[i] + new_data[i])

print(expected_result)

這導致:

[(0, 1, 2, 1, 1, 1, 0, 0, 0), (3, 4, 5, 0, 1, 0, 1, 0, 1)]

對於您的特定示例,以下代碼應該可以工作

Data = [(0,1,2),(3,4,5)]
new_data = [(1,1,1,0,0,0),(0,1,0,1,0,1)]
desired_result = [a+b for a,b in zip(Data,new_data)]

但是,我建議將您的數據作為numpy.array或作為pandas.DataFrame以便於操作。 您是否通過 csv 讀入數據?

暫無
暫無

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

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