Hy guys my teacher has assing me to get the integer from a row string in one column. This all thing is going to be by read a csv file with the help from python.So my terminal dosen't hit but i dont get nothing as a guide problem, i want from every row to take the integer and print them.
Here is my code :
import pandas as pd
tx = [ "T4.csv" ]
for name_csv in tx :
df = pd.read_csv( name_csv, names=["A"])
for row in df:
if row == ('NSIT ,A: ,'):
# i dont know how to use the split for to take the integer and print them !!!!
print("A",row)
else
# i dont know how to use the split for to take the integer and print them !!!!
print("B",row)
Also here is and what it have the the csv file :(i have the just them all in the column A)
NSIT ,A: ,-213
NSIT ,A: ,-43652
NSIT ,B: ,-39
NSIT ,A: ,-2
NSIT ,B: ,-46
At the end i have put my try on python, i hope you guys to understand the problem i have.
CodePudding user response:
df = pd.read_csv( "T4.csv", names=["c1", "c2", "c3"])
print(df.c3)
CodePudding user response:
Read the file one line at a time. Split each line on comma. Print the last item in the resulting list.
with open('T4.csv') as data:
for line in data:
len(tokens := line.split(',')) == 3:
print(tokens[2])
Alternative:
with open('T4.csv') as data:
d = {}
for line in data:
if len(tokens := line.split(',')) == 3:
_, b, c = map(str.strip, tokens)
d.setdefault(b, []).append(c)
for k, v in d.items():
print(k, end='')
print(*v, sep=',', end='')
print(f' sum={sum(map(int, v))}')
Output:
A:-213,-43652,-2 sum=-43867
B:-39,-46 sum=-85
CodePudding user response:
Your question was not very clear. So I assume you want to print out the 3rd column of the CSV file. I also think that you opened the CSV file in Excel, which is why you see that all the data is put in Column A.
A CSV (comma-separated values) file is a plain text file that contains data organised as a table of rows and columns, where each row represents a record, and each column represents a field or attribute of the form.
A newline character typically separates each row of data in a CSV file, and the values in each column are separated by a delimiter character, such as a comma (,). For example, here is a simple CSV file with three rows and three columns:
S.No, Student Name, Student Roll No.
1, Alpha, 123
2, Beta, 456
3, Gamma, 789
For a simple application like what you mention, Pandas might not be required. You can use the standard csvreader
library of Python to do this.
Please find the code below to print out the 3rd column of your CSV file.
import csv
with open("T4.csv") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
headers = next(csv_reader) # Get the column headers
print(headers[2]) # Print the 3rd column header
for row in csv_reader:
print(row[2]) # Print the 3rd column data