如何从 Python 中创建的 Dataframe 中删除索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37351172/
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
How to remove index from a created Dataframe in Python?
提问by controlfreak
I have created a Dataframe df
by merging 2 lists using the following command:
我df
使用以下命令通过合并 2 个列表创建了一个 Dataframe :
import pandas as pd
df=pd.DataFrame({'Name' : list1,'Probability' : list2})
But I'd like to remove the first column (The index column) and make the column called Name
the first column. I tried using del df['index']
and index_col=0
. But they didn't work. I also checked reset_index()
and that is not what I need. I would like to completely remove the whole index column from a Dataframe that has been created like this (As mentioned above). Someone please help!
但我想删除第一列(索引列)并将该列称为Name
第一列。我尝试使用del df['index']
和index_col=0
。但他们没有工作。我也检查过reset_index()
,这不是我需要的。我想从这样创建的数据框中完全删除整个索引列(如上所述)。有人请帮忙!
回答by jezrael
import pandas as pd
list1 = [1,2]
list2 = [2,5]
df=pd.DataFrame({'Name' : list1,'Probability' : list2})
print (df)
Name Probability
0 1 2
1 2 5
df.set_index('Name', inplace=True)
print (df)
Probability
Name
1 2
2 5
If you need also remove index name
:
如果您还需要删除索引name
:
df.set_index('Name', inplace=True)
#pandas 0.18.0 and higher
df = df.rename_axis(None)
#pandas bellow 0.18.0
#df.index.name = None
print (df)
Probability
1 2
2 5
回答by D. Whitt
If you want to save your dataframe to a spreadsheet for a report.. it is possible to format the dataframe to eliminate the index column using xlsxwriter.
如果要将数据框保存到报表的电子表格中.. 可以使用 xlsxwriter 格式化数据框以消除索引列。
writer = pd.ExcelWriter("Probability" + ".xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='Probability', startrow=3, startcol=0, index=False)
writer.save()
index=False will then save your dataframe without the index column.
index=False 然后将保存没有索引列的数据框。
I use this all the time when building reports from my dataframes.
从我的数据帧构建报告时,我一直使用它。