Reading Excel Strings in Python

I want to import rows of data saved in Excel CSV. How to save the data of each row as a list?

An Excel file has the following data type:

Name   B  C   D
ItemID 3  3   4
Height 5  5   7
Length 6  5   8

I want to save [B, C, D] in a list with a name Nameand [3,3,4] as a list with a name ItemID. I tried using the following code, but it always returns the last line of the file.

f = open('part.csv', 'r')
csv_f=csv.reader(f,delimiiter=',')
for row in csv_f:
    name.append(row[1])
    numid.append(row[2])
    height.append(row[3])
    length.append(row[4])
+4
source share
4 answers

I highly recommend considering using the pandas python data analysis library.

import pandas as pd

csv_df = pd.read_csv('part.csv')
df_T = csv_df.T

print df_T['ItemID'].tolist()
print df_T.index.tolist()
0
source

, , , . row = ['Name', 'B', 'C', 'D'].
, :

data = {}
with open('part.csv', 'r') as f:
    csv_f=csv.reader(f,delimiiter=',')
    for row in csv_f:
        data[row[0]] = row[1:]

:

{'Height': ['5', '5', '7'],
 'ItemID': ['3', '3', '4'],
 'Length': ['6', '5', '8'],
 'Name': ['B', 'C', 'D']}
+2

try it

with open('testdata.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        name.append(row['fieldname'])
+1
source

What you are trying to do is work with a DataFrame. Try using the pandas library as it simplifies many operations.

0
source

All Articles