在for循环中追加Pandas数据帧将导致ValueE

2024-06-17 12:31:51 发布

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

我想生成一个由for循环中生成的单独数据帧组成的数据帧。每个单独的数据帧由一个名称列、一个整数范围和一个列组成,这些列标识整数所属的类别(例如,五分位1到5)。如果我单独生成每个数据帧,然后将一个附加到另一个以创建“主”数据帧,那么就没有问题。但是,当我使用循环来创建每个单独的数据帧(在现实生活中我需要这样做)时,尝试将数据帧附加到主数据帧会导致:

ValueError: incompatible categories in categorical concat

我写了一个简单的循环来说明:

import numpy as np
import pandas as pd

# Define column names
colNames = ('a','b','c')

# Define a dataframe with the required column names
masterDF = pd.DataFrame(columns = colNames)

# A list of the group names
names = ['Group1','Group2','Group3']

# Create a dataframe for each group
for i in names:
    tempDF = pd.DataFrame(columns = colNames)
    tempDF['a'] = np.arange(1,11,1)
    tempDF['b'] = i
    tempDF['c'] = pd.cut(np.arange(1,11,1),
                        bins = np.linspace(0,10,6),
                        labels = [1,2,3,4,5])
    print(tempDF)
    print('\n')

    # Try to append temporary DF to master DF
    masterDF = masterDF.append(tempDF,ignore_index=True)

print(masterDF)

我希望数据帧看起来像:

     a       b  c
 0   1  Group1  1
 1   2  Group1  1
 2   3  Group1  2
 3   4  Group1  2
 4   5  Group1  3
 5   6  Group1  3
 6   7  Group1  4
 7   8  Group1  4
 8   9  Group1  5
 9  10  Group1  5
10  11  Group2  1
11  12  Group2  1
12  13  Group2  2
13  14  Group2  2
...
28  29  Group3  5
29  30  Group3  5

似乎可以通过将添加到tempDF中的类别按如下方式进行类型转换来获得部分解决方案:

tempDF['c'] = pd.cut(np.arange(1,11,1),
                     bins = np.linspace(0,10,6),
                     labels = [1,2,3,4,5]).astype('int')

但是,在这种情况下,类别(列“c”)现在显示为1.0、2.0等,而不是1、2等,因此并不理想。

有谁能解释一下为什么会这样,并提出一个更令人满意的解决方案。


Tags: 数据fornamesnp整数类别pdprint
1条回答
网友
1楼 · 发布于 2024-06-17 12:31:51

您可以首先将所有DataFrames附加到列表dfs,然后^{}

dfs = []
# Create a dataframe for each group
for i in names:
    tempDF = pd.DataFrame(columns = colNames)
    tempDF['a'] = np.arange(1,11,1)
    tempDF['b'] = i
    tempDF['c'] = pd.cut(np.arange(1,11,1),
                        bins = np.linspace(0,10,6),
                        labels = [1,2,3,4,5])
    print(tempDF)
    print('\n')

    # Try to append temporary DF to master DF
    dfs.append(tempDF)

masterDF = pd.concat(dfs, ignore_index=True)
print(masterDF)
     a       b  c
0    1  Group1  1
1    2  Group1  1
2    3  Group1  2
3    4  Group1  2
4    5  Group1  3
5    6  Group1  3
6    7  Group1  4
7    8  Group1  4
8    9  Group1  5
9   10  Group1  5
10   1  Group2  1
11   2  Group2  1
12   3  Group2  2
13   4  Group2  2
14   5  Group2  3
15   6  Group2  3
16   7  Group2  4
17   8  Group2  4
18   9  Group2  5
19  10  Group2  5
20   1  Group3  1
21   2  Group3  1
22   3  Group3  2
23   4  Group3  2
24   5  Group3  3
25   6  Group3  3
26   7  Group3  4
27   8  Group3  4
28   9  Group3  5
29  10  Group3  5

相关问题 更多 >