[英]read/write dictionary of strings, integers, and lists of strings from/to csv file
[英]Why Integers in csv file read as strings into pandas dataframe
在下面的 csv 文件中,有些列包含不同数据类型的数据,即有些行是整数,有些行是字符串。
"ip_v", "ittl", "olen", "mss", "OS_type"
"*", 64, 0, "*", "Windows"
4, 64, 0, 1430, "Linux"
"*", "64-", 0, 1460, "MAC-OS"
我将 csv 文件读入 pandas dataframe
df = pd.read_csv("file.csv")
并在 for 循环中遍历每一行并检查每个值的类型以进一步进行。
但是,尽管 csv 文件中的值类型不同,但在 python 中,所有值都被读取为strings
。 例如,当我检查每一行中"ittl"
列值的类型时,它们都读作字符串,但我希望row 0 and 1 to be int
, row 2 to be str
。
为什么我会遇到这个问题,这是怎么回事?
for index, row in df.iterrows():
print(row['ittl'], type(row['ittl']))
Output:
64 <class 'str'>
64 <class 'str'>
64- <class 'str'>
我不知道,但如果你想将你的列设为 int 类型,你可以这样做:
df['ittl'] = df['ittl'].astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.