python&pandas将大型数据帧拆分为多个数据帧并绘制图表

2024-05-14 12:41:03 发布

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

我和this case的情况相似。我正在做一个项目,它有一个大数据帧,大约有50万行。大约有2000名用户参与其中(我通过value_counts()计算一个名为NoUsager的列得到这个数字)。在

我想把数据帧分成几个数组/数据帧,以便以后绘图。(多个表示每个用户有一个数组/数据帧) 我得到的用户列表如下:

df.sort_values(by='NoUsager',inplace=True)
df.set_index(keys=['NoUsager'],drop=False,inplace=True)
users = df['NoUsager'].unique().tolist()

我知道后面是一个循环来生成更小的数据帧,但我不知道如何实现它。我结合了上面的代码,尝试了the case中的一个,但是没有解决方案。在

我该怎么处理它?在


编辑

我需要数据帧的直方图和盒线图。有了答案,我已经有了所有NoUsager的框线图。但是对于大量的数据,boxplot太小,无法读取。所以我想用NoUsager分割数据帧,并分别绘制它们。 我想要的图表:

  1. boxplot,column=DureeService,by=NoUsager
  2. boxplot,column=DureeService,by='Weekday`
  3. 直方图,每Weekday,by=DureeService

我希望这次解释得很好。在

数据类型:

^{pr2}$

数据帧示例:

Weekday NoUsager Periods Sens DureeService
Lun 000001 Matin + 00:00:05 
Lun 000001 Matin + 00:00:04 
Mer 000001 Matin + 00:00:07 
Dim 000001 Soir  - 00:00:02 
Lun 000001 Matin + 00:00:07 
Jeu 000001 Soir  - 00:00:04 
Lun 000001 Matin + 00:00:07 
Lun 000001 Soir  - 00:00:04 
Dim 000001 Matin + 00:00:05 
Lun 000001 Matin + 00:00:03 
Mer 000001 Matin + 00:00:04 
Ven 000001 Soir  - 00:00:03 
Mar 000001 Matin + 00:00:03 
Lun 000001 Soir  - 00:00:04 
Lun 000001 Matin + 00:00:04 
Mer 000002 Soir  - 00:00:04 
Jeu 000003 Matin + 00:00:50 
Mer 000003 Soir  - 00:06:51 
Mer 000003 Soir  - 00:00:08 
Mer 000003 Soir  - 00:00:10 
Jeu 000003 Matin + 00:12:35 
Lun 000004 Matin + 00:00:05 
Dim 000004 Matin + 00:00:05 
Lun 000004 Matin + 00:00:05 
Lun 000004 Matin + 00:00:05 

困扰我的是这些数据都不是数字,所以每次都要转换。在

提前谢谢!在


Tags: 数据用户dfby数字casemerdim
2条回答

不需要先分类。您可以尝试使用原始数据帧:

# import third-party libraries
import pandas as pd
import numpy as np
# Define a function takes the database, and return a dictionary
def splitting_dataframe(df):
    d = {}                                   # Define an empty dictionary
    nousager = np.unique(df.NoUsager.values) # Getting the NoUsage list
    for NU in nousager:                      # Loop over NoUsage list
        d[NU] = df[df.NoUsager == NU]        # I guess this line is what you want most
    return d                                 # Return the dictionary
dictionary = splitting_dataframe(df)  # Calling the function

在此之后,您可以通过以下方式调用特定NoUsager的数据帧:

^{pr2}$

希望这有帮助。在


编辑

如果您想绘制方框图,您是否尝试过:

df.boxplot(column='DureeService', by='NoUsager')

直接?此处提供更多信息:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.boxplot.html


编辑

如果您想为几个选定的“NoUsager”绘制框线图:

targets = [some selected NoUsagers]
mask = np.sum([df.A.values == targets[i] for i in xrange(len(targets))], dtype=bool, axis=0)
df[mask].boxplot(column='DureeService', by='NoUsager')

如果您想要一个选定的“NoUsager”的柱状图:

df[target NoUsager].hist(column='DureeService')

如果你还需要把它们分开,@Psidom的第一行就足够了。在

[g for _, g in df.groupby('NoUsager')]提供一个数据帧列表,其中每个数据帧包含一个唯一的NoUsager。但我认为你需要的是:

for k, g in df.groupby('NoUsager'):
    g.plot(kind = ..., x = ..., y = ...) etc..

相关问题 更多 >

    热门问题