关于pandas导入csv、excel数据后的数据类型能否自动将INT识别为CHAR类型

AI摘要
用户询问pandas读取CSV/Excel文件时,如何自动将所有推断为整型的列转换为字符型。建议使用dtype参数全局指定object类型,或读取后批量转换数据类型。

pandas里的read_csv,read_excel函数读取文件时,会自动猜测数据类型,很多时候猜测的INT类型其实都应该是CHAR类型,比如我导入的很多表格都是这样的,因为表很多,没法单独给某一列指定类型,可不可以有一种方法能够将识别到INT都自动转换为CHAR类型呢?

讨论数量: 3
Jason990420

要将 CSV 文件读入 Pandas DataFrame 并确保特定的整数列被解释为字符串,您可以使用 pd.read_csv() 函数中的 dtype 参数。

import pandas as pd

# Create a sample CSV file for demonstration
data = """col_int_as_str,col_other_int,col_float
12345,678,9.9
54321,987,1.1"""
with open("sample.csv", "w") as f:
    f.write(data)

# Read the CSV, specifying 'col_int_as_str' as 'string' dtype
df = pd.read_csv("sample.csv", dtype={'col_int_as_str': 'string'})

# Print the DataFrame and its dtypes to verify
print(df)
print("\nData Types:")
print(df.dtypes)
  col_int_as_str  col_other_int  col_float
0          12345            678        9.9
1          54321            987        1.1

Data Types:
col_int_as_str    string[python]
col_other_int              int64
col_float                float64
dtype: object

如果要 所有列都读成字符串

df = pd.read_csv("sample.csv", dtype="string")     # dtype=str
  col_int_as_str col_other_int col_float
0          12345           678       9.9
1          54321           987       1.1

Data Types:
col_int_as_str    string[python]
col_other_int     string[python]
col_float         string[python]
dtype: object

如果 CSV 没有表头(column 标题)

df = pd.read_csv("sample.csv", header=None, dtype="string")
       0    1    2
0  12345  678  9.9
1  54321  987  1.1

Data Types:
0    string[python]
1    string[python]
2    string[python]
dtype: object

pandas.read_csv()pandas.read_excel() 在此用法相同 !

9小时前 评论
zhwlyfx (楼主) 6小时前
Jason990420

只有 int 类型的栏位转成 string

int_cols = df.select_dtypes(include='int').columns
df[int_cols] = df[int_cols].astype("string")

栏位内可能同时有 int、float、str 等不同类型的值

# 对整个 DataFrame 每个栏位做处理
for col in df.columns:
    df[col] = df[col].apply(lambda x: str(x) if isinstance(x, int) else x)
5小时前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!