Home > Enterprise >  selecting one specific column out of a text file
selecting one specific column out of a text file

Time:06-28

I want to select just the second column of the below text file which is: 500, 1000, 1500, ..., 4500, 5000, 5500, ... , 21000

I have attached a picture of my text file below.

I have used the script below to do that, but I don't have the number 500 in my result:

with open("example", "r") as f:
    reader = csv.reader(f, delimiter =" ")
    second_column = list(zip(*reader))[3]

Can someone help me out with how to fix this problem?

enter image description here

CodePudding user response:

You can use the read_csv function from the pandas library. For instance:

import pandas as pd

data = pd.read_csv("data.csv", delimiter=",")

Select the right delimiter. What you will get is a pandas DataFrame. Then you can select your column of interest by using, for instance, the column header:

my_column = data["my_column"]

If you prefer working with numpy, you can convert the my_column series to a numpy array by using the to_numpy() method.

CodePudding user response:

Second column - index=1. In your code the index is 3. Must be 1.

with open("example", "r") as f:
    reader = csv.reader(f, delimiter =" ")
    second_column = list(zip(*reader))[1]
  • Related