Mark
Mark

Reputation: 1769

Pandas DataFrame, how get data elements without dtype and \nName

I uploaded a pandas dataframe with

import pandas as pd 
data = pd.read_csv("names.csv", header=None)

this dataframe contains names and surnames of people. Its size is (38,1). Anyway, when I tried to get the first name,

str(data.loc[1])

(I need a string) I obtain:

'0    John Smith\nName: 1, dtype: object'

Why? I would like to have:

'John Smith'

Upvotes: 1

Views: 924

Answers (2)

instinct246
instinct246

Reputation: 1002

The reason for the output you are getting is: 'data.loc[1]' is a pandas.core.series.Series object. When you convert it to str, the whole series with all its details gets converted to a string object.

This should give what you are looking for.

data.loc[1].values[0]

or

data.loc[1].tolist()[0]

or

data.loc[1,0]

The type of o/p is string - you may not have to convert it to string type further.

Upvotes: 5

ALollz
ALollz

Reputation: 59549

Since your csv contains a single column, use the squeeze argument of pd.read_csv. This will return a Series, which now allows you to select an individual value with .loc as Series are 1-D.


Sample Data: names.csv

foo
bar
bazz
boo
John Smith

Code

s = pd.read_csv('names.csv', header=None, squeeze=True)
s.loc[4]
#'John Smith'

Upvotes: 1

Related Questions