如何防止选择首行作为索引列

2024-10-01 09:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读取数据时遇到了一个问题,第一列被指定为索引列,即使我使用index_col=Noneindex_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写入csv

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 &royspried &成为索引列,即使我显式地写index_col=None

如何正确地得到patient列的原样和控制索引列是否存在

泰铢


Tags: csvnonedfreadindexcolstrongscore
1条回答
网友
1楼 · 发布于 2024-10-01 09:23:53

只需删除delim_whitespace=True,因为它在您的解决方案中使用了空格分隔符而不是tab,但这里只使用文件名为的sep='\t'参数:

df.to_csv('xgboost.txt', sep='\t', index=False)
read_df=pd.read_table(r'xgboost.txt', sep="\t") 
print (read_df)
        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

另一个想法是写入文件空格分隔符,这样delim_whitespace=True就可以很好地工作了:

df.to_csv('xgboost.txt', sep=' ', index=False)

read_df=pd.read_table(r'xgboost.txt', delim_whitespace=True) 

相关问题 更多 >