Python聚合函数(例如sum)不处理对象数据类型,但在转换时也不工作?

2024-05-13 00:04:03 发布

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

我正在从一个CSV文件导入数据,该文件包含文本、日期和数字列。我使用pandas.read_csv()来读入它,但我没有指定每列的数据类型。这是一个csv文件的剪辑(为粗劣的格式道歉)。你知道吗

现在这两列(total_imp_pmachar_value_aa503)的导入方式非常不同。我导入所有数字字段并创建一个名为base_varlist4的新数据帧,它只包含数字列。你知道吗

当我运行base_varlist4.dtypes时,我得到:

total_imp_pma          object
char_value_aa503      float64

如您所见,total_imp_pma作为对象导入。问题是如果我运行这个:

#calculate max, and group by obs_date
output_max_temp=base_varlist4.groupby('obs_date').max(skipna=True)

#reset obs_date to be treated as a column rather than an index
output_max_temp.reset_index()

#reshape temporary output to have 2 columns corresponding to variable and value
output_max=pd.melt(output_max_temp, id_vars='obs_date', value_vars=varlist4)

其中varlist4只是我的列列表,我得到了错误的total_imp_pma的最大值,但是得到了正确的char_value_aa503的最大值。你知道吗

从逻辑上讲,这意味着我应该将对象total_imp_pma更改为浮点或整数。但是,当我跑步时:

base_varlist4[varlist4] = base_varlist4[varlist4].apply(pd.to_numeric, errors='coerce')

然后继续做最大值,我仍然得到一个不正确的结果。你知道吗

这是怎么回事?为什么pandas.read_csv()将一些列作为object数据类型导入,而将其他列作为int64float64数据类型导入?为什么转换不起作用?你知道吗

我有一个理论,但我不知道如何解决它。我在源数据的两列中看到的唯一区别是total_imp_pma一直以来都是混合类型的单元格。例如,66979是一个General单元格,而有一个稍低一点的单元格,值为1,760.60作为number。你知道吗

我认为某些列中的混合单元格类型会导致pandas.read_csv()混淆,只会说“whelp,dunno this is,import it as a object”。你知道吗

。。。我该怎么解决这个问题?你知道吗

编辑:这是一个符合以下要求的MCVE。

CSV中的数据是:

Char_Value_AA503    Total_IMP_PMA
1293    19.9
1831    0.9
    1.2
243 2,666.50

代码为:

import pandas as pd

loc = r"xxxxxxxxxxxxxx"
source_data_name = 'import_problem_example.csv'
reporting_date = '01Feb2018'

source_data = pd.read_csv(loc + source_data_name)
source_data.columns = source_data.columns.str.lower()

varlist4 = ["char_value_aa503","total_imp_pma"]

base_varlist4 = source_data[varlist4]
base_varlist4['obs_date'] = reporting_date

base_varlist4[varlist4] =  base_varlist4[varlist4].apply(pd.to_numeric, errors='coerce')

output_max_temp=base_varlist4.groupby('obs_date').max(skipna=True)

#reset obs_date to be treated as a column rather than an index
output_max_temp.reset_index()

#reshape temporary output to have 2 columns corresponding to variable and value
output_max=pd.melt(output_max_temp, id_vars='obs_date', value_vars=varlist4)


""" Test some stuff"""

source_data.dtypes
output_max
source_data.dtypes

如您所见,total imp pma的最大值显示为19.9,而它应该是2666.50。你知道吗


Tags: csvtosourceoutputdatabasedatevalue