我在读取数据时遇到了一个问题,第一列被指定为索引列,即使我使用index_col=None
或index_col=None
。类似的问题发布为pandas read_csv index_col=None not working with delimiters at the end of each line
raw_data = {'patient': ['spried & roy']*5,
'obs': [1, 2, 3, 1, 2],
'treatment': [0, 1, 0, 1, 0],
'score': ['strong', 'weak', 'normal', 'weak', 'strong'],
}
df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])
patient obs treatment score
0 spried & roy 1 0 strong
1 spried & roy 2 1 weak
2 spried & roy 3 0 normal
3 spried & roy 1 1 weak
4 spried & roy 2 0 strong
df.to_csv('xgboost.txt', sep='\t', index=False)
read_df=pd.read_table(r'xgboost.txt', header=0,index_col=None, skiprows=0, skipfooter=0, sep="\t",delim_whitespace=True)
read_df
patient obs treatment score
spried & roy 1 0 strong
& roy 2 1 weak
& roy 3 0 normal
& roy 1 1 weak
& roy 2 0 strong
我们可以看到patient
列被分为spried &
和roy
和spried &
成为索引列,即使我显式地写index_col=None
如何正确地得到patient
列的原样和控制索引列是否存在
泰铢
只需删除
delim_whitespace=True
,因为它在您的解决方案中使用了空格分隔符而不是tab
,但这里只使用文件名为的sep='\t'
参数:另一个想法是写入文件空格分隔符,这样
delim_whitespace=True
就可以很好地工作了:相关问题 更多 >
编程相关推荐