python中删除unnamed_python - Pandas: how to get rid of `Unnamed:` column in a dataframe

I have a situation wherein sometimes when I read a csv from df I get an unwanted index-like column named unnamed:0. This is very annoying! I have tried

merge.to_csv('xy.df', mode = 'w', inplace=False)

which I thought was a solution to this, but I am still getting the unnamed:0 column! Does anyone have an idea on this?

python

pandas

ipython

|

this question asked Apr 9 '16 at 15:47

Michael Perdue 519 3 14

|

1 Answers

1

---Accepted---Accepted---Accepted---

It's the index column, pass index=False to not write it out, see the docs

Example:

In [37]:

df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))

pd.read_csv(io.StringIO(df.to_csv()))

Out[37]:

Unnamed: 0 a b c

0 0 0.109066 -1.112704 -0.545209

1 1 0.447114 1.525341 0.317252

2 2 0.507495 0.137863 0.886283

3 3 1.452867 1.888363 1.168101

4 4 0.901371 -0.704805 0.088335

compare with:method to do it from the documentation without rewriting the whole DF. Does anyone know how to do it DataFrame: ## x1 x2##0 206 214##1 226 234##2 245 253##3 265 272##4 283 291 Desired output: ## x1 x2##0 206 na

In [38]:

pd.read_csv(io.StringIO(df.to_csv(index=False)))

Out[38]:

a b c

0 0.109066 -1.112704 -0.545209

1 0.447114 1.525341 0.317252

2 0.507495 0.137863 0.886283

3 1.452867 1.888363 1.168101

4 0.901371 -0.704805 0.088335

You could also optionally tell read_csv that the first column is the index column by passing index_col=0:

In [40]:

pd.read_csv(io.StringIO(df.to_csv()), index_col=0)

Out[40]:

a b c

0 0.109066 -1.112704 -0.545209

1 0.447114 1.525341 0.317252

2 0.507495 0.137863 0.886283

3 1.452867 1.888363 1.168101

4 0.901371 -0.704805 0.088335

|

this answer

edited Apr 9 '16 at 16:16 answered Apr 9 '16 at 15:50

EdChum 97.7k 17 122 137      Thanks EdChum! Annoyance eliminated! To think that I was just reading the docs and looking for this solution. Somehow I was not properly comprehending. –

Michael Perdue Apr 9 '16 at 15:51

|

I tried: x=pandas.DataFrame(...)s = x.take([0], axis=1) And s gets a DataFrame, not a Series. answer 1 >>accepted >>> import pandas as pd>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})>>> df x y0 1 41 2 52 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值