Combine cells from one column into one string

3k Views Asked by At
df = pd.read_csv(filename.csv)
corpus = df.corpus

How can I combine series of text strings (from one column) into a list?

from column 'corpus': row 1: Hail Mary.
row 2: Hi Bob.
row 3: Hey Sue.

into [Hail Mary. Hi Bob. Hey Sue.]

Looking for a list with len(list)=1.

4

There are 4 best solutions below

1
Joe On BEST ANSWER

If I understood you correctly:

df = pd.read_csv(your_file)
l = [' '.join(df['col'])]

Input:

          col
0  Hail Mary.
1     Hi Bob.
2    Hey Sue.

Output:

['Hail Mary. Hi Bob. Hey Sue.']
2
Somesh On
    my_list = []

    for i in range(1,ws.max_row):
        if(len(my_list) == 0):
            my_list.append(ws.cell(row=i,column=1).value)   #assuming the value in 1st column
        else:
            my_list[0] += ws.cell(row=i,column=1).value

    for i in my_list:
        print(i)
2
sur.la.route On

test.csv:

Hail Mary. Hi Bob. Hey Sue.

python:

import csv
data = []
with open('test.csv','rb') as csvfile:
    for row in csvfile:
        data.append(row.strip())
print data

output: ['Hail Mary.', 'Hi Bob.', 'Hey Sue.']

3
chriscberks On
import pandas as pd

df = pd.read_csv('example.csv')

result = [' '.join([row for row in df['column_name']])]

Output of result:

['Hail Mary. Hi Bob. Hey Sue.']