python - 为什么 pd.concat 将结果类型从 int 更改为 object?
问题描述
我正在用 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
出现的地方。
虽然我从诸如此类的其他帖子中了解到Pandas 更改了dtype
,但non-null
我无法使用建议的解决方案解决我的问题。
我该如何解决?
解决方案
我发现另一篇文章提到必须使用 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)
到我的代码中并且它起作用了。
推荐阅读
- c# - 刷新 DataSource 后获取 TreeList 的状态?
- java -
从字符串的末尾删除所有内容 - python-3.x - 将键、值附加到 dict
- elasticsearch - 具有许多文本字段的弹性搜索性能不佳
- python - dash核心下拉回调更新问题
- redirect - 如何在 ASP.NET Core 中强制执行 HTTPS
- node.js - MongoNetworkError:连接 4 到 localhost:27017 超时
- android - Android 从 BaseActivity 注入到从 BaseActivity 扩展的所有类
- google-cloud-platform - 在 GCP 文件夹中创建项目需要哪些权限?
- javascript - 将 java 脚本代码转换为 java 类