python - 根据值拆分 pandas 数据框

标签 python pandas

我想将 pandas 数据帧拆分为组,以便单独处理每个组。我的“value.csv”文件包含以下数字

num tID y x height width
2   0   0   0   1   16
2   1   1   0   1   16 
5   0   1   0   1   16 
5   1   0   0   1   8 
5   2   0   8   1   8 
6   0   0   0   1   16 
6   1   1   0   1   8 
6   2   1   8   1   8
2   0   0   0   1   16
2   1   1   0   1   16 
5   0   1   0   1   16 
5   1   0   0   1   8 
5   2   0   8   1   8 
6   0   0   0   1   16 
6   1   1   0   1   8 
6   2   1   8   1   8

我想根据 tID 列中 0 的起始值来分割数据,就像前 4 个分隔一样。

第一:

2   0   0   0   1   16
2   1   1   0   1   16 

第二:

5   0   1   0   1   16 
5   1   0   0   1   8 
5   2   0   8   1   8 

第三:

6   0   0   0   1   16 
6   1   1   0   1   8 
6   2   1   8   1   8

第四:

2   0   0   0   1   16
2   1   1   0   1   16 

为此,我尝试使用 if 来分割它,但没有成功,有什么有效的想法吗?

    import pandas as pd
    statQuality = 'value.csv'
    df = pd.read_csv(statQuality, names=['num','tID','y','x','height','width'])


    df2 = df.copy()
    df2.drop(['num'], axis=1, inplace=True)

    x = []

    for index, row in df2.iterrows():
        if row['tID'] == 0:
            x = []
            x.append(row)
            print(x)
        else:
            x.append(row)

最佳答案

用途:

#create groups by consecutive values
s = df['num'].ne(df['num'].shift()).cumsum()
#create helper count Series for duplicated groups like `2_0`, `2_1`...
g = s.groupby(df['num']).transform(lambda x: x.factorize()[0])
#dictionary of DataFrames
d = {'{}_{}'.format(i,j): v.drop('num', axis=1) for (i, j), v in df.groupby(['num', g])}
print (d)
{'2_0':    tID  y  x  height  width
0    0  0  0       1     16
1    1  1  0       1     16, '2_1':    tID  y  x  height  width
8    0  0  0       1     16
9    1  1  0       1     16, '5_0':    tID  y  x  height  width
2    0  1  0       1     16
3    1  0  0       1      8
4    2  0  8       1      8, '5_1':     tID  y  x  height  width
10    0  1  0       1     16
11    1  0  0       1      8
12    2  0  8       1      8, '6_0':    tID  y  x  height  width
5    0  0  0       1     16
6    1  1  0       1      8
7    2  1  8       1      8, '6_1':     tID  y  x  height  width
13    0  0  0       1     16
14    1  1  0       1      8
15    2  1  8       1      8}

关于python - 根据值拆分 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240593/

相关文章:

python - 如何表示未使用的函数参数?

python - 如何从 python 操作 cmd.exe,以便输出显示在 cmd.exe 窗口中

python - 在类之间共享 pandas 数据框

python - 将不同目录中的粘贴文件复制到一个文件夹

python - dask dataframe.persist() 是否保留下一个查询的结果?

python - 在 pandas 数据框中使用正则表达式匹配组的性能

python - 为 pandas 列创建类别计数字典

python - 使用 Pandas 从另一个数据框中的信息过滤数据框

python - 从函数声明中收集参数名称

python - Pandas:如何提取一段时间内的行?