To convert files in rows into columns in Python or Excel

Asked 2 years ago, Updated 2 years ago, 46 views

There are files in Python or Excel with rows.

For example:

Name Kim Jun

Name Reason

Name of Kim Pie

Gender male

Gender Men

File recorded as above

Name: Kim Jun Yiyu Kim Pie

sex a person a man.

Is there any way I can change it like this? I looked it up, but it didn't come out, so I'm asking. It doesn't come out except how to express values such as Kim Jun, reason, and others in columns as 0, 1.

python excel

2022-09-22 20:57

2 Answers

It is convenient to use the itertools module.

'''
The contents of sample.csv are as follows.

name,aaaa
name,bbbb
name,ccc
age,10
age,20
age,30
'''

import csv
import itertools

with open('d:/sample.csv', 'r') as f:
    reader = csv.reader(f)
    for key, group in itertools.groupby(reader, lambda i:i[0]):
        print('{} => {}'.format(key, list(map(lambda i:i[1], group))))

name => ['aaaa', 'bbbb', 'ccc']
age => ['10', '20', '30']


2022-09-22 20:57

A more efficient method is to create a pivot by using a dataframe for the pandas, but first of all, it's an example of a basic module.

import csv
import itertools

with open('d:/sample.csv', 'r') as f:
    reader = csv.reader(f)
    keys, vals = set(), []
    for key, group in itertools.groupby(reader, lambda i:i[0]):
        keys.add(key)
        vals.append(list(map(lambda i:i[1], group)))

    print('\t'.join(keys))
    for name, val in zip(vals[0], vals[1]):print('{}\t{}'.format(name, val))

name    age
aaaa    10
bbbb    20
ccc     30


2022-09-22 20:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.