0

I am fairly new to Python and have encountered a small but (what seems to be a) very difficult problem.

I have a txt file which contains the following:

-2      2.1     -0.365635756
0       2.4      0.347433737
2       2.5      0.263774619
4       3.5     -0.244930974
6       4.2     -0.004564913

My aim is to somehow extract separate rows/columns from the file in Python to use as lists or arrays (again, I'm fairly new to this). So for example, how would I make the list [-2, 0, 2, 4, 6] using the data from the first column?

I currently have the following code in my work:

import numpy as np

with open('Numbers.txt', 'r') as f:
    fcontents = f.read()
    print(fcontents)

x = np.array(fcontents)

The objective of this is to write a program that uses arrays to calculate different variables given in our project instructions.

2

3 Answers 3

1

This might be a job for pandas:

import pandas as pd

df = pd.read_fwf('Numbers.txt', header=None)
first_col = df[0]

assert first_col.mean() == 2
assert first_col.median() == 2
assert sum(first_col) == 10

References:

Sign up to request clarification or add additional context in comments.

1 Comment

Yay! Pandas rules! But for this particular file format i'd use pd.read_fwf()
0

I haven't used numpy but if you want to separate into columns you can do this kind of thing

col1 = []
col2 = []
col3 = []

with open('Numbers.txt', 'r') as f:
    for line in f:
        first, second, third = line.split()
        col1.append(first)
        col2.append(second)
        col3.append(third)

print(col1)
print(col2)
print(col3)

which outputs

['-2', '0', '2', '4', '6']
['2.1', '2.4', '2.5', '3.5', '4.2']
['-0.365635756', '0.347433737', '0.263774619', '-0.244930974', '-0.004564913']

Comments

0

You can import your data as a numpy.array

import numpy as np

data = np.genfromtxt('Numbers.txt', unpack=True).T

Then, retrieving columns/rows is as simple as indexing/slicing a numpy.array

print(data[1,:])
print(data[:,1])

this will results in

[ 0.          2.4         0.34743374]
[ 2.1  2.4  2.5  3.5  4.2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.