1

Have a question. If I run this code, I get exactly what I have in the CSV. My target is to get a text/data/csv file which would look like this: ['red', 'green', 'blue'] meaning:

  1. Converting a single column into a row.
  2. While converting to row, entering a comma to differentiate values.

Is it possible to do it through Python? Is there any online materials I can look into?

3
  • 3
    Hi, welcome to StackOverflow. Since you are new, please check out How to Ask and the help center. Please make sure your questions are self contained as possible. Do not post links to code, do not use images of code, post the relevant code in the question itself as formatted text. Here is some info on formatting your code. Commented Mar 20, 2020 at 20:28
  • 1
    Interesting question. It is very hard to help with code. You need to post your code, not images of code. Commented Mar 20, 2020 at 20:32
  • 1
    Is it possible to do it through Python? Yes. Is there any online materials I can look into? That's explicitly off-topic. Please see How to Ask, help center. Commented Mar 20, 2020 at 21:48

3 Answers 3

1

The csv file is read sequentially, that is, you will always get the data back one row at a time. However, you can build an array of just the values you want as you read the file and discard the rest of the data.

import csv

with open('example.csv') as csvfile:
    colours = []
    for row in csv.reader(csvfile, delimiter=','):
         if len(row) <= 3:
              continue
         colours.append(row[3])
Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve this code using pandas. Try this code:

import pandas as pd
df = pd.read_csv("input csv file")
df = df.T
df.to_csv("output csv file")

Update if this is what you are looking for

Comments

0

Without using any extra libraries, you could write a function that takes a specific column, and returns that column as an array.

Such a function might look like this.

def column_to_row(col_num, csv):
    return list(row[col_num] for row in csv)

Then you can extract whatever column you want, or iterate through the whole csv like this.

new_csv = []
for i in range(0, len(csv[0]):
    new_csv = new_csv.append(column_to_row(i, csv))

1 Comment

this won't exactly work with a csv.reader which is an iterator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.