从中的计数方法访问数据

2024-04-25 22:57:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用count方法从数据帧返回信息,如下所示:

df = pd.DataFrame.from_csv(csv_file)

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

这将返回:

DatetimeIndex: 4641 entries, 2014-01-08 02:02:05.740845 to 2014-01-08 02:58:56.405287

Data columns (total 3 columns):

OPTION 4641 non-null values

SELL 4641 non-null values

BUY 4641 non-null values

dtypes: float64(2), object(1)>

这正是我想要的信息,但是我想在代码中访问计数(本例中为4641)或“非空值”之类的数据,而不仅仅是打印出来。我应该如何访问此类数据?你知道吗


Tags: columnscsv数据方法from信息dataframedf
1条回答
网友
1楼 · 发布于 2024-04-25 22:57:30

首先,您有效地创建了groups的数据。所以这是更好的服务如下。你知道吗

grouped = df.groupby('OPTION')

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

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

关于聚合split combine的一个很好的参考是官方的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

相关问题 更多 >