简体   繁体   English

为什么 csv 文件中的整数作为字符串读入 pandas dataframe

[英]Why Integers in csv file read as strings into pandas dataframe

In the following csv file, some columns contain data with different datatypes, ie some rows are integers and some rows are strings.在下面的 csv 文件中,有些列包含不同数据类型的数据,即有些行是整数,有些行是字符串。

"ip_v", "ittl", "olen", "mss",  "OS_type"
 "*",    64,       0,     "*",   "Windows"
  4,     64,       0,    1430,   "Linux"
 "*",   "64-",     0,    1460,   "MAC-OS"

I read the csv file into pandas dataframe我将 csv 文件读入 pandas dataframe
df = pd.read_csv("file.csv")
And iterate through each row in a for loop and check the type of each value to proceed further.并在 for 循环中遍历每一行并检查每个值的类型以进一步进行。
But, though the values types are different in csv file, in python all values are read as strings .但是,尽管 csv 文件中的值类型不同,但在 python 中,所有值都被读取为strings For example, when I check the type for "ittl" column values in each row, they all read as string but I was expecting row 0 and 1 to be int and row 2 to be str .例如,当我检查每一行中"ittl"列值的类型时,它们都读作字符串,但我希望row 0 and 1 to be introw 2 to be str
Why am I facing this problem, what is going on?为什么我会遇到这个问题,这是怎么回事?

for index, row in df.iterrows():
    print(row['ittl'], type(row['ittl']))

Output:
64    <class 'str'>
64    <class 'str'>
64-   <class 'str'>

i dont know but if you want to make your column as an int type you can make this:我不知道,但如果你想将你的列设为 int 类型,你可以这样做:

df['ittl'] = df['ittl'].astype(int)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 csv 文件读取/写入字符串、整数和字符串列表的字典 - read/write dictionary of strings, integers, and lists of strings from/to csv file pandas dataframe:保存并阅读excel表单| 将整数作为字符串处理 - pandas dataframe : save & read excel sheet | handling integers as strings 在熊猫数据框中将字符串转换为整数 - Convert strings to integers in pandas dataframe 为什么从带有 Pandas 的 a.CSV 文件中读取的数据在转换为整数后不能使用 matplotlib 绘制? - Why can data read from a .CSV file with Pandas not be plotted using matplotlib after turning it into integers? 为什么`pandas.read_csv` 不是`pandas.DataFrame.to_csv` 的倒数? - Why is `pandas.read_csv` not the reciprocal of `pandas.DataFrame.to_csv`? 如何使用 pandas 将度分秒 (DMS) 数据直接从 a.CSV 文件读取到 dataframe 作为字符串? - How to read Degree Minute Seconds (DMS) data directly from a .CSV file using pandas into a dataframe as strings? 将 csv 文件读入列表并将字符串转换为整数 Python - Read csv file into list and convert the strings into integers Python 在csv文件中编写一个混合整数和浮点数的pandas DataFrame - Write a pandas DataFrame mixing integers and floats in a csv file 将 CSV 文件读入 Pandas Dataframe 分块导致单个目标 Dataframe - Read CSV File into Pandas Dataframe with Chunking Resulting in a Single Target Dataframe 将列表写入pandas dataframe到csv,从csv读取dataframe并再次转换为列表而没有字符串 - write lists to pandas dataframe to csv, read dataframe from csv and convert to lists again without having strings
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM