python - 为什么 pd.concat 将结果类型从 int 更改为 object?

标签 python pandas dataframe types concatenation

我正在使用 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由于 non-null,Pandas 更改了 dtype,我无法使用建议的解决方案解决我的问题。

我该如何解决这个问题?

最佳答案

我找到了另一个 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) 并且成功了。

关于python - 为什么 pd.concat 将结果类型从 int 更改为 object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915603/

相关文章:

python - 使用子图时如何使用 matplotlib.pyplot.xticks 或类似的?

java - 如何设置PATH同时使用Java和Python

以 pandas 数据框和列名作为输入的 Python 函数

python - 从空格分隔的字符串创建 Pandas DataFrame

python - 输入动态分配的属性

python - 使用列表中的搜索词从文本中获取字数的最快方法?

python - 使用自定义颜色渐变填充两条线之间的区域

python - 如何在 one-hot 编码的 pandas 数据框中找到列的正索引?

python - 旋转 Panda DataFrame 的列名

python - 计算 pandas DF 列子集的均值或方差