[英]How to read column names from csv as integer in pandas
It seems the default for pd.read_csv()
is to read in the column names as str
.似乎
pd.read_csv()
的默认值是将列名读取为str
。 I can't find the behavior documented and thus can't find where to change it.我找不到记录的行为,因此找不到更改它的位置。
Is there a way to tell read_csv()
to read in the column names as integer?有没有办法告诉
read_csv()
将列名作为整数读入?
Or maybe the solution is specifying the datatype when calling pd.DataFrame.to_csv()
.或者也许解决方案是在调用
pd.DataFrame.to_csv()
时指定数据类型。 Either way, at the time of writing to csv, the column names are integers and that is not preserved on read.无论哪种方式,在写入 csv 时,列名都是整数,读取时不会保留。
The code I'm working with is loosely related to this ( credit ):我正在使用的代码与此(信用)松散相关:
df = pd.DataFrame(index=pd.MultiIndex.from_arrays([[], []]))
for row_ind1 in range(3):
for row_ind2 in range(3, 6):
for col in range(6, 9):
entry = row_ind1 * row_ind2 * col
df.loc[(row_ind1, row_ind2), col] = entry
df.to_csv("df.csv")
dfr = pd.read_csv("df.csv", index_col=[0, 1])
print(dfr.loc[(0, 3), 6]) # KeyError
print(dfr.loc[(0, 3), "6"]) # No KeyError
我的临时解决方案是:
dfr.columns = dfr.columns.map(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.