首页 文章

从Pandas中的count方法访问数据

提问于
浏览
0

我通过这种方式使用count方法从DataFrame返回信息:

df = pd.DataFrame.from_csv(csv_file)

for i in df['OPTION'].unique():
   count = df.loc[df['OPTION'] == i].count
   print count

这会返回:

DatetimeIndex:4641条目,2014-01-08 02:02:05.740845至2014-01-08 02:58:56.405287数据列(共3列):选项4641非空值卖出4641非空值买入4641非-null values dtypes:float64(2),object(1)>

这是我所追求的那种信息,但我想访问我的代码中的计数(本例中为4641)或“非空值”等数据,而不仅仅是打印出来 . 我该如何访问这类数据?

1 回答

  • 1

    首先,您正在有效地创建 groups 数据 . 所以这更好地服务如下 .

    grouped = df.groupby('OPTION')
    

    接下来,您希望从此 grouped 对象获取特定组 . 所以你迭代组,提取计数(基本上是索引的长度),提取特定列(例如卖出)

    for name, group in grouped:
        print("Option name: {}".format(name))
        # Count of entries for this OPTION
        print("Count: {}".format(len(group.index)))
        # Accessing specific columns, say SELL
        print("SELL for this option\n")
        print(group["SELL"])
        # Summary for SELL for this option
        print("Summary\n")
        print(group["SELL"].describe())
    

    聚合拆分组合的一个很好的参考是官方的Pandas文档 . 从同一个引用 .

    By “group by” we are referring to a process involving one or more of the following steps
    Splitting the data into groups based on some criteria
    Applying a function to each group independently
    Combining the results into a data structure
    

相关问题