【问题标题】:Display/Print one column from a DataFrame of Series in Pandas在 Pandas 中显示/打印 Series 的 DataFrame 中的一列
【发布时间】:2018-02-17 18:14:09
【问题描述】:

我创建了以下系列和数据框:

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'])

我只想显示/打印 DataFrame 中的一列(有或没有标题行):

要么

Adam 
Bob 
Cathy

或者:

Sweet
Candy
Chocolate

我尝试了以下代码,但没有成功:

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])

我可以在一行简单的代码中完成吗?

【问题讨论】:

  • @JohnGalt 嗨,我开始学习 pandas 并尝试掌握不同函数和方法的用法。
  • 您是否使用 IPython 并以 10 Minutes to pandas 开头?
  • @JohnGalt 我正在运行 Jupyter Notebook 的本地会话并在 Coursera 上学习课程

标签: python-2.7 pandas dataframe series


【解决方案1】:

通过使用to_string

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


 Adam
  Bob
Cathy

【讨论】:

  • to_string 更有意义。请选择这个答案
【解决方案2】:

用于打印名称列

df['Name']

【讨论】:

    【解决方案3】:

    不确定你真正追求的是什么,但如果你想准确地打印你所拥有的,你可以这样做:

    选项 1

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

    选项 2

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多