簡體   English   中英

Pandas read_json() 不強制轉換列 dtypes

[英]Pandas read_json() doesn't cast column dtypes

我正在使用 Pandas read_json() 讀取 json 文件。 如果我只是閱讀它:

輸入:

df_grades = pd.read_json("students_grades.json")
df_grades.dtypes

output:

names                          object
gender                         object
race/ethnicity                 object
parental level of education    object
lunch                          object
test preparation course        object
math score                     object
reading score                  object
writing score                  object
dtype: object

它只是將 json 文件的每一列讀取為 object。 具體來說,出於我的目的,“數學分數”、“閱讀分數”和“寫作分數”列需要是整數。 出於某種原因,使用“read_json”的“dtype”屬性不起作用。

輸入:

df_grades = pd.read_json("students_grades.json", dtype={'math score': 'int64',
                                                        'reading score': 'int64',
                                                        'writng score': 'int64'})
df_grades.dtypes

output:

names                          object
gender                         object
race/ethnicity                 object
parental level of education    object
lunch                          object
test preparation course        object
math score                     object
reading score                  object
writing score                  object
dtype: object

由於某種原因,Dtypes 保持不變。 可能是什么原因?

提前致謝!

該文檔可以作為答案嗎?

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df.dtypes

col1    int64
col2    int64
dtype: object

df.astype('int32').dtypes

col1    int32
col2    int32
dtype: object

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM