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

北慕城南 提交于 2019-12-08 06:03:50

问题


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?


回答1:


By using to_string

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


 Adam
  Bob
Cathy



回答2:


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



回答3:


For printing the Name column

df['Name']


来源:https://stackoverflow.com/questions/46122910/display-print-one-column-from-a-dataframe-of-series-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!