如何在 Pandas 中读取带有行名称的数据框的 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27814743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:49:08  来源:igfitidea点击:

How to read CSV file with of data frame with row names in Pandas

pythonpandas

提问by pdubois

I have a CSV file (tmp.csv) that looks like this:

我有一个 CSV 文件 ( tmp.csv),如下所示:

        x       y       z
bar     0.55    0.55    0.0
foo     0.3     0.4     0.1
qux     0.0     0.3     5.55

It was created with Pandas this way:

它是用 Pandas 以这种方式创建的:

    In [103]: df_dummy 
    Out[103]: 
          x     y     z
    bar  0.55  0.55  0.00
    foo  0.30  0.40  0.10
    qux  0.00  0.30  5.55

   In [104]: df_dummy.to_csv("tmp.csv",sep="\t")   

What I want to do is to read that CSV into the same dataframe representation. I tried this but doesn't give what I want:

我想要做的是将该 CSV 读入相同的数据帧表示形式。我试过这个,但没有给出我想要的:

In [108]: pd.io.parsers.read_csv("tmp.csv",sep="\t")
Out[108]: 
  Unnamed: 0     x     y     z
0        bar  0.55  0.55  0.00
1        foo  0.30  0.40  0.10
2        qux  0.00  0.30  5.55

What's the right way to do it?

正确的做法是什么?

回答by Roman Pekar

You can use index_colparameter:

您可以使用index_col参数:

>>> pd.io.parsers.read_csv("tmp.csv",sep="\t",index_col=0)
        x     y     z
bar  0.55  0.55  0.00
foo  0.30  0.40  0.10
qux  0.00  0.30  5.55