簡體   English   中英

如何通過 python 將列表數據添加到 CSV 文件的第一列,該文件有 256 列文件?

[英]How to add the List data to the first column of the CSV file, which has 256 columns file via python?

我有一個 CSV 文件,它有 255 列和 16,000 行數據,我想將包含 16,000 個數據的數據列表添加到我的 CSV 文件的第一列。

我嘗試使用的代碼是

# Append the name of the file to List
path = 'C:/Users/User/Desktop/Guanlin_CNN1D/CNN1D/0.3 15 and 105 circle cropped'
list = os.listdir(path)
List = []
for a in list:
    List.append(str(a))   

## Load the to-be-added CSV file
data = pd.read_csv('C:/Users/User/Desktop/Guanlin_CNN1D/CNN1D/0.3 15 and 105 for toolpath recreatation.csv',sep=',', engine='python' ,header=None)
tempdata = pd.DataFrame(data)
features = tempdata.values[:, 1:]
file_num = tempdata.values[:, 0]

# add the List to first columns of CSV file
Temp = {List,file_num,features}
temp = pd.DataFrame(Temp)
temp

結果顯示

類型錯誤:不可散列類型:“列表”

如何重寫代碼?

提前致謝!

我認為您只需要使用 dataframe 插入方法即可。 看起來您正在嘗試創建一個新的 dataframe 但我認為沒有必要。 下面的示例在第零個 position 處插入一個新列。 看起來您正在嘗試從字典中制作新的 dataframe; 此鏈接有一些簡單的示例,用於使用列表和字典填充 dataframe。 我認為在這種情況下,行數和列數不應該是你關心的問題。

import numpy as np
import pandas as pd

np.random.seed(0)

df = pd.DataFrame(np.random.randint(0, 100, size=(5, 5)), columns=list('ABCDE'))
print(df)

df.insert(0,column='newcol', value=np.random.randint(0, 100, size=(5)))
print()
print(df)

df.to_csv( r'data.csv', index=False, header=True)

將產生這個 output

    A   B   C   D   E
0  44  47  64  67  67
1   9  83  21  36  87
2  70  88  88  12  58
3  65  39  87  46  88
4  81  37  25  77  72

   newcol   A   B   C   D   E
0       9  44  47  64  67  67
1      20   9  83  21  36  87
2      80  70  88  88  12  58
3      69  65  39  87  46  88
4      79  81  37  25  77  72

暫無
暫無

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

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