0

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.

3
  • You desired input and output look equals. Are you trying to transpose the dataframe? Or do you want a single column as output? Commented Sep 8, 2019 at 21:28
  • @Valentino its not same. It's kind of multiple column. Each row value will be new column. Commented Sep 8, 2019 at 22:06
  • I edited the display to properly show the array layouts. Commented Sep 8, 2019 at 22:11

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but I want multiple type of output. Like each row convert into column.
@ShamjibhaiSolanki Updated with .stack
Voyla its something helpful. Thanks buddy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.