Python 重置列索引熊猫?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42284617/
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
Reset Column Index Pandas?
提问by MrClean
>>> data = data.drop(data.columns[[1,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]], axis=1)
>>> data = data.drop(data.index[[0,1]],axis = 0)
>>> print(data.head())
0 2 3 4 20
2 500292014600 .00 .00 .00 NaN
3 500292014600 100.00 .00 .00 NaN
4 500292014600 11202.00 .00 .00 NaN
>>> data = data.reset_index(drop = True)
>>> print(data.head())
0 2 3 4 20
0 500292014600 .00 .00 .00 NaN
1 500292014600 100.00 .00 .00 NaN
2 500292014600 11202.00 .00 .00 NaN
How come when i use df.reset_index the index of my columns is not reset? How do I go about resetting this index to 0,1,2,3,4?
为什么当我使用 df.reset_index 时,我的列的索引没有重置?如何将此索引重置为 0、1、2、3、4?
回答by Pablo Fonseca
Try the following:
请尝试以下操作:
df = df.T.reset_index(drop=True).T
回答by Patrick Nieto
Try replacing the column names:
尝试替换列名:
>>> import numpy as np
>>> import pandas as pd
>>> my_data = [[500292014600, .00, .00, .00, np.nan],
[500292014600, 100.00, .00, .00, np.nan],
[500292014600, 11202.00, .00, .00, np.nan]]
>>> df = pd.DataFrame(my_data, columns=[0,2,3,4,20])
>>> df
0 2 3 4 20
0 500292014600 0.0 0.0 0.0 NaN
1 500292014600 100.0 0.0 0.0 NaN
2 500292014600 11202.0 0.0 0.0 NaN
>>> df.columns = range(df.shape[1])
>>> df
0 1 2 3 4
0 500292014600 0.0 0.0 0.0 NaN
1 500292014600 100.0 0.0 0.0 NaN
2 500292014600 11202.0 0.0 0.0 NaN
回答by Vaishali
In pandas, by index you essentially mean row index. As you can see in your data, the row index is reset after drop and reset_index().
在 Pandas 中,索引本质上是指行索引。正如您在数据中看到的,行索引在 drop 和 reset_index() 之后被重置。
For columns, you need to rename them, you can do something like
对于列,您需要重命名它们,您可以执行以下操作
data.columns = [ 0,1,2,3,4]
回答by ashish patel
If you have numpy imported with import numpy as np
如果你有 numpy 导入 import numpy as np
simply set the columns to zero based indexes with data.columns = [np.arange(0,data.shape[1])]
只需将列设置为零基索引 data.columns = [np.arange(0,data.shape[1])]
回答by Jeff Hernandez
Pure Python Implementation
纯 Python 实现
We enumerate
the columns
of the dataframe to create an array of items. Then we map
the function reversed
to each item in the array. Lastly, we create and input the dictionary as the parameter columns
in the data frame object method rename
.
我们enumerate
使用columns
数据框来创建一个项目数组。然后我们对数组中的每个项目map
执行函数reversed
。最后,我们创建并输入字典作为columns
数据框对象方法中的参数rename
。
columns = dict(map(reversed, enumerate(df.columns)))
df = df.rename(columns=columns)
df.head()
Results:
结果:
0 1 2 3 4
0 500292014600 0.0 0.0 0.0 NaN
1 500292014600 100.0 0.0 0.0 NaN
2 500292014600 11202.0 0.0 0.0 NaN