0

Here I have a dataset with three inputs. Three inputs x1,x2,x3. Here I want to read just x2 column and in that column data stepwise row by row.

Here I wrote a code. But it is just showing only letters.

Here is my code

data = pd.read_csv('data6.csv')
row_num =0
x=[]
for col in data:
if (row_num==1):
    x.append(col[0])
row_num =+ 1
print(x)

result : x1,x2,x3

What I expected output is:

expected output x2 (read one by one row)
65
32
14
25
85
47
63
21
98
65
21
47
48
49
46
43
48
25
28
29
37

Subset of my csv file :

x1  x2  x3
6   65  78
5   32  59
5   14  547
6   25  69
7   85  57
8   47  51
9   63  26
3   21  38
2   98  24
7   65  96
1   21  85
5   47  94
9   48  15
4   49  27
3   46  96
6   43  32
5   48  10
8   25  75
5   28  20
2   29  30
7   37  96

Can anyone help me to solve this error?

1
  • Try data = pd.read_csv('data6.csv', usecols=['x2'])? Commented Sep 19, 2019 at 8:40

3 Answers 3

2

If you want list from x2 use:

x = data['x2'].tolist()
Sign up to request clarification or add additional context in comments.

Comments

2

I am not sure I even get what you're trying to do from your code. What you're doing (after fixing the indentation to make it somewhat correct):

  • Iterate through all columns of your dataframe
  • Take the first character of the column name if row_num is equal to 1.

Based on this guess:

import pandas as pd

data = pd.read_csv("data6.csv")
row_num = 0
x = []
for col in data:
    if row_num == 1:
        x.append(col[0])
    row_num = +1
print(x)

What you probably want to do:

import pandas as pd
data = pd.read_csv("data6.csv")
# Make a list containing the values in column 'x2'
x = list(data['x2'])

# Print all values at once:
print(x)

# Print one value per line:
for val in x:
    print(val)

Comments

1

When you are using pandas you can use it. You can try this to get any specific column values by using list to direct convert into a list.For loop not needed

import pandas as pd
data = pd.read_csv('data6.csv')
print(list(data['x2']))

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.