Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display/Print one column from a DataFrame of Series in Pandas

I created the following Series and DataFrame:

import pandas as pd

Series_1 = pd.Series({'Name': 'Adam','Item': 'Sweet','Cost': 1})
Series_2 = pd.Series({'Name': 'Bob','Item': 'Candy','Cost': 2})
Series_3 = pd.Series({'Name': 'Cathy','Item': 'Chocolate','Cost': 3})`
df = pd.DataFrame([Series_1,Series_2,Series_3], index=['Store 1', 'Store 2', 'Store 3'])

I want to display/print out just one column from the DataFrame (with or without the header row):

Either

Adam 
Bob 
Cathy

Or:

Sweet
Candy
Chocolate

I have tried the following code which did not work:

print(df['Item'])
print(df.loc['Store 1'])
print(df.loc['Store 1','Item'])
print(df.loc['Store 1','Name'])
print(df.loc[:,'Item'])
print(df.iloc[0])

Can I do it in one simple line of code?

like image 316
Kane Chew Avatar asked Sep 08 '17 18:09

Kane Chew


People also ask

How do I get columns from Panda series?

You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.

How do I get a single column from a Dataframe?

This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. Passing a list in the brackets lets you select multiple columns at the same time.

Can you slice a Pandas series?

Pandas str. slice() method is used to slice substrings from a string present in Pandas series object. It is very similar to Python's basic principal of slicing objects that works on [start:stop:step] which means it requires three parameters, where to start, where to end and how much elements to skip.


3 Answers

For printing the Name column

df['Name']
like image 85
Tarun Singh Avatar answered Oct 20 '22 19:10

Tarun Singh


By using to_string

print(df.Name.to_string(index=False))


 Adam
  Bob
Cathy
like image 32
BENY Avatar answered Oct 20 '22 18:10

BENY


Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate
like image 29
piRSquared Avatar answered Oct 20 '22 17:10

piRSquared