0

How to read the first cell from my csv file and store it as a variable

for example, my list is

header 1 header 2
AM
Depth Value
10 20
30 122
60 222

how can I read the (AM) cell and store it as "x" variable? and how I can I ignore AM cell later on and start my data frame from my headers (Depth, value)?

Abdullah
  • 19
  • 4

3 Answers3

0

You should be able to get a specific row/column using indexing. iloc should be able to help.

For example, df.iloc[0,0] returns AM.

Also, pandas.read_csv allows you to skip rows when reading the data, You can use pd.read_csv("test.csv", sep="\t",skiprows=1) to skip first row.

Result:

0     10     20
1     30    122
2     60    222
Jerry
  • 60
  • 1
  • 5
0

Hi I am using dummy csv file which is generated using data you posted in this question.

import pandas as pd
# read data 
df = pd.read_csv('test.csv')

File contents are as follows:

    header 1   header 2
0   AM         NaN
1   Depth      Value
2   10         20
3   30         122
4   60         222

One can use usecols parameter to access different columns in the data. If you are interested in just first column in this case it can be just 0 or 1. Using 0 or 1 you can access individual columns in the data.

You can save contents of this to x or whichever variable you want as follows:

# Change usecols to load various columns in the data 
x = pd.read_csv('test.csv',usecols=[0])

Header:

# number of line which you want to use as a header set it using header parameter
pd.read_csv('test.csv',header=2)

    Depth   Value
0   10      20
1   30      122
2   60      222
Sayali Sonawane
  • 12,289
  • 5
  • 46
  • 47
  • Please [don’t post images of code, error messages, or other textual data.](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557) – tripleee Dec 29 '22 at 11:31
  • 1
    @tripleee, I have now removed all the images and added code directly to answer. Thanks – Sayali Sonawane Dec 29 '22 at 11:44
0

Use pd.read_csv and then select the first row:

import pandas as pd
df = pd.read_csv('your file.csv')
x = df.iloc[0]['header 1']

Then, to delete it, use df.drop:

df.drop(0, inplace=True)
Pythoneer
  • 319
  • 1
  • 16