【问题标题】:Why does pd.concat change the resulting type from int to object?为什么 pd.concat 将结果类型从 int 更改为 object?
【发布时间】:2019-05-23 17:53:03
【问题描述】:

我正在使用 Pandas 解析几个 csv 文件,并将它们连接到一个大数据帧中。然后,我想groupby 并计算mean()

这是一个示例数据框:

df1.head()

   Time  Node  Packets
0     1     0        0
2     1     1        0
4     1     2        0
6     1     3        0
8     1     4        0

df1.info(verbose=True)

<class 'pandas.core.frame.DataFrame'>
Int64Index: 27972 entries, 0 to 55942
Data columns (total 3 columns):
Time       27972 non-null int64
Node       27972 non-null int64
Packets    27972 non-null int64
dtypes: int64(3)
memory usage: 874.1 KB
None

然后我将它们连接起来(为简单起见,三个数据帧)

df_total = pd.concat([df1, df2, df3])

df_total.info(verbose=True) 结果

<class 'pandas.core.frame.DataFrame'>
Int64Index: 83916 entries, 0 to 55942
Data columns (total 3 columns):
Time       83916 non-null object
Node       83916 non-null object
Packets    83916 non-null object
dtypes: object(3)
memory usage: 2.6+ MB
None

最后,我试试:

df_total = df_total.groupby(['Time'])['Packets'].mean()

这就是错误pandas.core.base.DataError: No numeric types to aggregate 出现的地方。

虽然我从其他帖子(例如 this)了解到,Pandas 更改了 dtype 是因为 non-null,但我无法通过建议的解决方案解决我的问题。

我该如何解决这个问题?

【问题讨论】:

  • 您可能想尝试returned_errors = [] &lt;br&gt;results = [] &lt;br&gt;for group in df_total.groupby(['Time'])['Packets']:&lt;br&gt; try:&lt;br&gt; results.append ([group[0], group[1].mean()]) &lt;br&gt;except: &lt;br&gt;returned_error.append(group) 这应该会为您提供任何没有错误(如果有)的组的结果,并告诉您哪些组导致了错误。

标签: python pandas dataframe types concat


【解决方案1】:

我发现另一个 post 提到数据帧必须使用 dtype 进行初始化,否则它们是对象类型

Did you initialize an empty DataFrame first and then filled it? If so that's probably
why it changed with the new version as before 0.9 empty DataFrames were initialized 
to float type but now they are of object type. If so you can change the 
initialization to DataFrame(dtype=float).

所以我在我的代码中添加了df_total = pd.DataFrame(columns=['Time', 'Node', 'Packets'], dtype=int),它起作用了。

【讨论】:

    【解决方案2】:
     df_total.info(verbose=True)
    

    您的此语句将信息作为对象提供,因此连接存在问题,每个值都不是 int,因此对象的平均值是不可能的。

    【讨论】:

      猜你喜欢
      • 2018-10-01
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多