簡體   English   中英

python 將數據從列表寫入 CSV 文件

[英]python write data from the list to a CSV a file

我正在使用以下代碼將數據列表寫入 CSV 文件,其中 python 我正在使用以下代碼。

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")

以上代碼失敗,請求您幫助解決相同的問題

您沒有在腳本中的任何位置調用indexcolumn變量。

只需定義創建DataFrameindexcolumn列表。

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")

我認為您需要使用+創建列表以進行連接並傳遞給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

暫無
暫無

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

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