Shamji Solanki
Shamji Solanki

Reputation: 25

Converting csv row into csv columns

Hello I am trying to make one csv from another csv file.

Below is my input file in csv.

1  2
3  4
5  6

And my desired output like

1
2
3
4
5
6

Basically I am trying to convert each row into column.

csvfile = open('main.csv', 'r')
textcsv = csv.reader(csvfile, delimiter=',')


for row in textcsv:
    list_ = list(row)
    column = pd.DataFrame(list_)
    outputDF = pd.concat([outputDF, column], axis=1)
outputDF.to_csv(output.csv, sep=',',  index=False)

I got the output which convert row in column but not repeated.

Upvotes: 0

Views: 192

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62373

Use pd.DataFrame.stack:

df = pd.read_csv('test.csv')
print(df)

enter image description here

df2 = pd.DataFrame(df.stack())
df2.reset_index(inplace=True, drop=True)
print(df2)

enter image description here

df2.to_csv('output.csv', sep=',',  index=False)

Upvotes: 2

Related Questions