读取csv时删除 pandas 中的索引列 [英] Removing index column in pandas when reading a csv
问题描述
我有以下代码可导入CSV文件.有3列,我想将其中的前两个设置为变量.当我将第二列设置为变量效率"时,索引列也会被添加.如何摆脱索引列?
I have the following code which imports a CSV file. There are 3 columns and I want to set the first two of them to variables. When I set the second column to the variable "efficiency" the index column is also tacked on. How can I get rid of the index column?
df = pd.DataFrame.from_csv('Efficiency_Data.csv', header=0, parse_dates=False)
energy = df.index
efficiency = df.Efficiency
print efficiency
我尝试使用
del df['index']
设置后
energy = df.index
我在另一篇文章中找到的
,但结果为"KeyError:'index'"
which I found in another post but that results in "KeyError: 'index' "
推荐答案
DataFrames 和 Series 始终具有索引.尽管它显示在列旁边,但它不是列,这就是为什么del df['index']
不起作用的原因.
DataFrames and Series always have an index. Although it displays alongside the column(s), it is not a column, which is why del df['index']
did not work.
如果要用简单的序号替换索引,请使用df.reset_index()
.
If you want to replace the index with simple sequential numbers, use df.reset_index()
.
要了解为什么存在索引以及如何使用索引,请参见例如到熊猫10分钟.
To get a sense for why the index is there and how it is used, see e.g. 10 minutes to Pandas.
这篇关于读取csv时删除 pandas 中的索引列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!