如何将Int64Index转换为Index(从CSV读取)?

时间:2020-06-24 04:29:48

标签: python pandas

我有一个CSV文件,内容为:

enter image description here

然后我通过以下方式读取此文件:

A = pd.read_csv("MyTest2.csv")
A.columns

输出为

Index(['ID', '202005'], dtype='object')

但是,如果我运输数据框并删除一些未使用的列,则通过:

A = pd.read_csv("MyTest2.csv")
A = A.T
A = A.rename(columns=A.iloc[0])
A = A.drop(A.index[0])
A.columns

输出将变为:

Int64Index([1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243], dtype='int64')

我的问题是我想使用A [“ 1234”]读取列值,而不是A [1234](不带双引号)。

如何将Int64Index转换为Index?还是在传输计算期间防止索引成为Int64Index(或RangeIndex)的正确方法?

1 个答案:

答案 0 :(得分:1)

  • 使用IDstr列转换为.astype类型
A = pd.read_csv("MyTest2.csv")  # create the dataframe

A.ID = A.ID.astype('str')  # convert ID to a str type
  • 读文件时设置dtype
A = pd.read_csv('MyTest2.csv', dtype={'ID': str})