I need to convert 3 columns into 2 rows using python.
col1 col2 col3
A 2 3
B 4 5
col1 col2
A 2
A 3
B 4
B 5
*我的代碼 hdr = ['col1', 'col2'] final_output=[] for row in rows: output = {} output1 = {} output = { A : row.get(col1), B: row.get(col2 )} output1 = { A: row.get(col1), B: row.get(col3)}
final_out.append(output)
final_out.append(output1)
with open(tgt_file.csv, w) as tgt_file:
csv_writer=csv.DictWriter(tgt_file, fieldnames=hdr, delimiter=',')
csv_writer.writeheader()
csv_writer.writerows(final_output)
uj5u.com熱心網友回復:
import pandas as pd
### this is the sample data
df = pd.DataFrame(data= [['A',2, 3],['B',4, 5]],
columns =['col1', 'col2', 'col3'])
### this is the solution
ef = [] # create an empty list
for i,row in df.iterrows():
ef.append([row[0], row[1]]) # append first column first
ef.append([row[0], row[2]]) # append 2nd column second
df = pd.DataFrame(data=ef,columns=['col1','col2']) # recreate the dataframe
備注:可能有更高級的解決方案,但我認為這是可讀的
uj5u.com熱心網友回復:
您可以嘗試使用 pd.melt
df = pd.melt(df, id_vars=["col1"],value_name = 'col2').drop(['variable'],axis=1)
然后你可以在“col1”上對資料框進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359251.html
上一篇:網頁抓取資料
下一篇:用額外的間距在csv檔案上書寫
