Python 2.7 将列设置为索引时更改数据类型
我正在重新索引多个文件夹中的文件。文件最初看起来如下所示:Python 2.7 将列设置为索引时更改数据类型,python-2.7,pandas,Python 2.7,Pandas,我正在重新索引多个文件夹中的文件。文件最初看起来如下所示: Combined Percent 0101 50 0102 25 0104 25 Combined Percent 101 50 102 25 104 25 然后,我使用以下代码创建一个新索引,它是文件夹中所有文件索引的并集: import pandas as pd from glob import glob folders=(r'C:\pathw
Combined Percent
0101 50
0102 25
0104 25
Combined Percent
101 50
102 25
104 25
然后,我使用以下代码创建一个新索引,它是文件夹中所有文件索引的并集:
import pandas as pd
from glob import glob
folders=(r'C:\pathway_to_folders')
for folder in os.listdir(folders):
path=os.path.join(folders,folder)
filenames=glob(os.path.join(path+'/*.csv'))
def rfile(fn):
return pd.read_csv(fn, dtype='str', index_col=0)
dfs = [rfile(fn) for fn in filenames]
idx = dfs[0].index
for i in range(1, len(dfs)):
idx = idx.union(dfs[i].index)
print idx
当我将列Combined
设置为索引列时,dfs
现在如下所示:
Combined Percent
0101 50
0102 25
0104 25
Combined Percent
101 50
102 25
104 25
有没有办法保持索引的格式与原始列相同,或者操纵我的代码使其不必设置索引?我认为这仍然是一个长期存在的错误,您无法设置数据类型并指定与索引列相同的列,您必须将此作为第二步:
def rfile(fn):
return pd.read_csv(fn, dtype=str).set_index('Combined')
它应该能正常工作,
pd.read\u csv(fn,dtype={'Combined':str},index\u col=0)
能正常工作吗?它不能。可能是因为数据帧正在转换为列表,其中有一行dfs=[rfile(fn)for fn in filenames]
?如果没有设置索引列,数据类型是否会保留pd.read\u csv(fn,dtype=str)
?是的,它只会在设置索引列时更改。我认为这是一个长期存在的错误,如果您试图指定数据类型并设置索引列,那么它就不起作用,您需要作为第二步执行:返回pd.read\u csv(fn,dtype=str)。设置索引(“组合”)