python将列表中的数据写入CSV文件

时间:2021-03-10 10:47:29

标签: python python-3.x pandas dataframe

我正在处理下面的代码,用 python 将数据列表写入 CSV 文件 我正在使用以下代码。

import pandas as pd
df = pd.read_csv ("input.csv")
#From column name Test2 take count value of entry which is simple
simp = df.Test2.value_counts().Simple
list1 = [2, 5, 3, 3, 3]
#multiplying the above list value with the count of simple from input CSV
simplelist = [i * simp for i in list1]
print(simplelist)
# till here its working. Its printing as expected [24, 60, 36, 36, 36]
# I need to write the CSV with above value 1 to 5 from above list with Type as Simple
df1 = pd.DataFrame[(simplelist)]
index=['Simple', '0']
columns=['Type', 'Value1', 'Value2', 'Value3', 'Value4', 'Value5']
df1.to_excel("output.xlsx")

以上代码失败,请求您帮助解决相同的问题

2 个答案:

答案 0 :(得分:1)

您没有在脚本的任何地方调用 indexcolumn 变量。

只需定义创建 indexcolumnDataFrame 列表。

import pandas as pd
df = pd.read_csv ("input.csv")
#From column name Test2 take count value of entry which is simple
simp = df.Test2.value_counts().Simple
list1 = [2, 5, 3, 3, 3]
#multiplying the above list value with the count of simple from input CSV
simplelist = [i * simp for i in list1]
print(simplelist)

df1 = pd.DataFrame(simplelist, index=['Simple', '0'], columns=['Type', 'Value1', 'Value2', 'Value3', 'Value4', 'Value5'])
df1.to_excel("output.xlsx")

答案 1 :(得分:0)

我认为您需要使用 + 创建列表才能加入并传递给 DataFrame 构造函数:

simplelist = [24, 60, 36, 36, 36]

columns=['Type', 'Value1', 'Value2', 'Value3', 'Value4', 'Value5']
df1 = pd.DataFrame([['Simple'] + simplelist], columns=columns)

print (df1)
     Type  Value1  Value2  Value3  Value4  Value5
0  Simple      24      60      36      36      36