Search code examples
pythonjsondataframeconcatenationexport-to-csv

how to concatenate after list. Append for each item


suppose I have a,b,c (each is index values, subject values and text values) I created list and then created list with append each of them

the output should be

id subject text
1 subject1 text1
2 subject2 text2

and so on and I want it to extract it like that also to CSV in columns.

now I have them only in one column in CSV

column
1
subject1
text1
2
subject2
text2

How can I extract them to columns instead of rows?

data = []
#df = pd.DataFrame()
for row in res:
            result=( ''.join(row[0]))
            p = Payload(result)
            data.append(p.a)
            data.append(p.b)
            data.append(p.c)
          
            #data_new=print(a+b+c)
            #data_new =(''.join(data))
            data_new=np.concatenate([data])
            
            
#col = pd.DataFrame(data)  
                
df = pd.DataFrame(data_new)
print(df)

#df.values.reshape(100, 1)

#print(df)

  
df.to_csv('test.csv', sep='\t', encoding='utf-8', index=False)             
            #df.loc[len(df.ind

Any suggestions?

Thank you in advance


Solution

  • Looking at your code, to have three columns add to list data dictionaries with three keys:

    data = []
    for row in res:
        p = Payload("".join(row[0]))
        data.append({"id": p.a, "subject": p.b, "text": p.c})
    
    df = pd.DataFrame(data)
    print(df)
    df.to_csv("test.csv", sep="\t", encoding="utf-8", index=False)