[英]How to add the List data to the first column of the CSV file, which has 256 columns file via python?
I have a CSV file which has 255 columns and 16,000 rows of data, and I want to add a list of data which contains 16,000 data to the first column of my CSV file.我有一个 CSV 文件,它有 255 列和 16,000 行数据,我想将包含 16,000 个数据的数据列表添加到我的 CSV 文件的第一列。
The code I tried to use is我尝试使用的代码是
# 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
The result shows结果显示
TypeError: unhashable type: 'list'类型错误:不可散列类型:“列表”
How to rewrite the code?如何重写代码?
Thanks in advance!提前致谢!
I think you simply need to use the dataframe insert method.我认为您只需要使用 dataframe 插入方法即可。 It looks like you are trying to create a new dataframe but I think it is not necessary.
看起来您正在尝试创建一个新的 dataframe 但我认为没有必要。 Below example inserts a new column at the zeroth position.
下面的示例在第零个 position 处插入一个新列。 It looks like you were trying to make a new dataframe from a dict;
看起来您正在尝试从字典中制作新的 dataframe; this link has some easy examples on way to populate a dataframe with lists and dicts.
此链接有一些简单的示例,用于使用列表和字典填充 dataframe。 I think the number of rows and columns should not be a concern for you in this case.
我认为在这种情况下,行数和列数不应该是你关心的问题。
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)
will produce this output将产生这个 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.