Csv string to array python

Python csv string to array

You can convert a string to a file object using io.StringIO and then pass that to the csv module:

from io import StringIO import csv scsv = """text,with,Polish,non-Latin,letters 1,2,3,4,5,6 a,b,c,d,e,f gęś,zółty,wąż,idzie,wąską,dróżką, """ f = StringIO(scsv) reader = csv.reader(f, delimiter=',') for row in reader: print('\t'.join(row)) 

simpler version with split() on newlines:

reader = csv.reader(scsv.split('\n'), delimiter=',') for row in reader: print('\t'.join(row)) 

Or you can simply split() this string into lines using \n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.

On Python 2 you have to import StringIO as

from StringIO import StringIO 

Solution 2

Simple — the csv module works with lists, too:

>>> a=["1,2,3","4,5,6"] # or a = "1,2,3\n4,5,6".split('\n') >>> import csv >>> x = csv.reader(a) >>> list(x) [['1', '2', '3'], ['4', '5', '6']] 

Solution 3

The official doc for csv.reader() https://docs.python.org/2/library/csv.html is very helpful, which says

file objects and list objects are both suitable

import csv text = """1,2,3 a,b,c d,e,f""" lines = text.splitlines() reader = csv.reader(lines, delimiter=',') for row in reader: print('\t'.join(row)) 

Solution 4

And while the module doesn’t directly support parsing strings, it can easily be done:

import csv for row in csv.reader(['one,two,three']): print row 

Just turn your string into a single element list.

Importing StringIO seems a bit excessive to me when this example is explicitly in the docs.

Solution 5

As others have already pointed out, Python includes a module to read and write CSV files. It works pretty well as long as the input characters stay within ASCII limits. In case you want to process other encodings, more work is needed.

The Python documentation for the csv module implements an extension of csv.reader, which uses the same interface but can handle other encodings and returns unicode strings. Just copy and paste the code from the documentation. After that, you can process a CSV file like this:

with open("some.csv", "rb") as csvFile: for row in UnicodeReader(csvFile, encoding="iso-8859-15"): print row 

Источник

How to convert a Python csv string to array?

The first approach is by using the split() method. This method takes a parameter, and delimiters the character at which the string should be split. Since the input is a csv, which is comma-separated we will be setting the delimiter as comma and split the string into array.

Читайте также:  Python pack struct example

The split() method in Python is a string manipulation function that divides a larger string into multiple smaller strings. The strings are returned as a list by the split() method.

Example

In the example given below, we are taking a CSV string as input and we are converting it into an array −

str1 = "Hello,Everyone,Welcome,to,Tutorialspoint" print("The given CSV string is") print(str1) print("Converting the given CSV string into array") res = list(map(str.strip, str1.split(','))) print(res)

Output

The output of the above example is as follows −

The given CSV string is Hello,Everyone,Welcome,to,Tutorialspoint Converting the given CSV string into array ['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

Using inner.split() and splitlines()

The second appch is by using inner.split() and splitlines(). This approach is used if the input CSV string is multi-line. In this case, first we should split the lines so we will use splitlines() method for splitting at new line character. After splitting at new line, we should split each line at comma using the inner.split() method, then we should combine them into a single list.

Example

In the example given below, we are taking a multi-line CSV string as input and we are converting it into array using inner.split() and splitlines()

s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA" print("The given CSV string is") print(s) print("Converting the given CSV string into array") res = list(map(str.strip, s_inner.split(',')) for s_inner in s.splitlines()) print((res))

Output

The output of the above example is as follows −

The given CSV string is 1, John Doe, Boston, USA 2, Jane Doe, Chicago, USA Converting the given CSV string into array [, ]

Using reader() method of csv library

The third approach is by using the reader() method of csv library. This method takes a CSV string as input and converts it into an array. This method can also be used for multi−line outputs but we have to convert the multi-line using splitlines() method.

Example

In the example given below, we are taking a CSV string as input and we are converting it into array using reader() method −

import csv str1 = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA".splitlines() print("The given CSV string is") print(str1) print("Converting the given CSV string into array") x = csv.reader(str1) print(list(x))

Output

The output of the above example is given below −

The given CSV string is ['1, John Doe, Boston, USA', '2, Jane Doe, Chicago, USA'] Converting the given CSV string into array [['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]

Источник

Python CSV String to Array: 7 Methods to Convert CSV String into an Array using Python

Learn the different methods to convert a CSV string to an array using Python. From using the csv module to NumPy and pandas, find the best method for your project.

  • Using the csv module to parse a CSV string into a list of lists
  • Using the split() method to split a CSV string into an array
  • Converting a CSV file to a NumPy array using np.loadtxt()
  • Writing a NumPy array to a CSV file using np.savetxt()
  • Using io.StringIO and the csv module to convert a string to an array
  • Using pandas to load a CSV string into a DataFrame and then convert it to a NumPy array
  • Using str.join() method to convert a list to a comma-separated string and str.split() method to convert a comma-separated string to a list
  • Additional code samples for converting a CSV string to an array using Python
  • Conclusion
  • How do I split a CSV string into an array in Python?
  • How do you read a CSV file into an array in Python?
  • How to parse CSV text in Python?
  • How do you convert a string object to an array in Python?
Читайте также:  Как узнать php хостинга

If you have worked with tabular data in Python, then you know that a CSV file is one of the most common formats for storing and exchanging data. However, sometimes you may need to convert a CSV string to an array to use it in your Python code.

In this post, we will explore seven different methods to convert a CSV string to an array using Python. By the end of this post, you will have a good understanding of the various ways to parse a CSV string into an array and be able to choose the best method for your specific use case.

Using the csv module to parse a CSV string into a list of lists

The csv module in Python provides functionality for reading and writing CSV files. It allows you to read a CSV string line by line and convert it into a list of lists of string values. Here’s how you can do it:

import csvcsv_string = "name,age,gender\nJohn,30,Male\nJane,25,Female\n" lines = csv_string.strip().split('\n') csv_list = [] for line in lines: csv_list.append(line.split(',')) print(csv_list) 

In the above code, we first split the CSV string into a list of lines using the split() method. Next, we iterate over each line and split it by the comma delimiter to get a list of string values. Finally, we append each list to a new list called csv_list to get a list of lists.

Using the split() method to split a CSV string into an array

The split() method in Python can be used to split a string based on a delimiter. You can use this method to split a CSV string into a list of string values. Here’s how you can do it:

csv_string = "name,age,gender\nJohn,30,Male\nJane,25,Female\n" csv_list = [line.split(',') for line in csv_string.strip().split('\n')] print(csv_list) 

In the above code, we use a list comprehension to split each line of the CSV string by the comma delimiter and get a list of string values. This creates a list of lists that we can use as an array.

Converting a CSV file to a NumPy array using np.loadtxt()

NumPy is a popular library in Python for numerical analysis and scientific computing. It provides functionality for working with arrays and matrices. You can use the np.loadtxt() method in NumPy to load a CSV file into a NumPy array. Here’s how you can do it:

import numpy as npcsv_file = 'data.csv' delimiter = ',' csv_array = np.loadtxt(csv_file, delimiter=delimiter) print(csv_array) 

In the above code, we use the np.loadtxt() method to load a CSV file into a NumPy array. We pass the filename and delimiter string as arguments to the method. This creates a 2-dimensional NumPy array that we can use as an array.

Writing a NumPy array to a CSV file using np.savetxt()

You can also use NumPy to save a NumPy array to a CSV file using the np.savetxt() method. Here’s how you can do it:

import numpy as npcsv_file = 'data.csv' delimiter = ',' csv_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) np.savetxt(csv_file, csv_array, delimiter=delimiter) 

In the above code, we create a NumPy array and save it to a CSV file using the np.savetxt() method. We pass the filename and array as arguments to the method. This creates a CSV file that we can use as an array.

Читайте также:  Python idle предыдущая команда

Using io.StringIO and the csv module to convert a string to an array

You can also use the io.StringIO class in Python to convert a string to a file object. This file object can then be passed to the csv module to convert it into a list of lists. Here’s how you can do it:

import csv import iocsv_string = "name,age,gender\nJohn,30,Male\nJane,25,Female\n" csv_file = io.StringIO(csv_string) csv_list = list(csv.reader(csv_file)) print(csv_list) 

In the above code, we first create a StringIO object from the CSV string using the io.StringIO() method. Next, we pass this file object to the csv.reader() method to get a list of lists of string values. This creates a list of lists that we can use as an array.

Using pandas to load a CSV string into a DataFrame and then convert it to a NumPy array

Pandas is another popular library in Python for working with tabular data. You can use pandas to load a CSV string into a DataFrame and then convert it to a NumPy array. Here’s how you can do it:

import pandas as pd import numpy as npcsv_string = "name,age,gender\nJohn,30,Male\nJane,25,Female\n" df = pd.read_csv(pd.compat.StringIO(csv_string)) csv_array = df.to_numpy() print(csv_array) 

In the above code, we use the pd.read_csv() method to load the CSV string into a DataFrame. We then convert the DataFrame to a NumPy array using the to_numpy() method. This creates a 2-dimensional NumPy array that we can use as an array.

Using str.join() method to convert a list to a comma-separated string and str.split() method to convert a comma-separated string to a list

Finally, you can also use the str.join() method to convert a list to a comma-separated string and the str.split() method to convert a comma-separated string to a list. Here’s how you can do it:

csv_string = "name,age,gender\nJohn,30,Male\nJane,25,Female\n" csv_list = csv_string.strip().split('\n') csv_list = [line.split(',') for line in csv_list] csv_flat_list = [item for sublist in csv_list for item in sublist] csv_array = np.array(csv_flat_list).reshape(len(csv_list), -1) print(csv_array) 

In the above code, we first split the CSV string into a list of lines using the split() method. Next, we split each line by the comma delimiter to get a list of string values. We then use a list comprehension to flatten the list of lists into a flat list. Finally, we convert the flat list to a NumPy array using the np.array() method and reshape it to create a 2-dimensional NumPy array.

Additional code samples for converting a CSV string to an array using Python

In Python , in particular, python csv string to array code example

Conclusion

In this post, we covered seven different methods to convert a CSV string to an array using Python. We explored using the csv module, split() method, NumPy, io, pandas, and str.join() and str.split() methods to convert CSV string to an array. By understanding these methods, you can work with tabular data in Python more efficiently and effectively.

Источник

Оцените статью