Pandas DataFrame 重新索引列问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12962765/
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
Pandas DataFrame reindex column issue
提问by WonderSteve
I've been trying to figure this out for the last couple of hours...
在过去的几个小时里,我一直试图弄清楚这一点......
I have a list that I want to use as columns for DataFrames:
我有一个列表,我想用作 DataFrame 的列:
totalColumns = [a, b, c, d, e, f.....z]
I have several data frames that look like this:
我有几个看起来像这样的数据框:
DataFrameOne:
数据帧一:
b f j
1 12 5 6
2 4 99 2
3 10 77 16
DataFrameTwo:
数据框二:
a k y
1 2 25 46
2 7 54 76
3 34 67 101
4 45 24 54
and many more...
还有很多...
I want to reindex all the data frames according to totalColumns. For example, after reindexing, DataFrameOne would look like this:
我想根据 totalColumns 重新索引所有数据框。例如,重新索引后,DataFrameOne 将如下所示:
DataFrameOne:
数据帧一:
a b c......f.....j......z
1 NaN 5 NaN....5.....6......NaN
2 NaN 99 NaN....99....2......NaN
3 NaN 77 NaN....77....16.....NaN
So I used the reindex method:
所以我使用了 reindex 方法:
DataFrameOne.reindex(columns=totalColumns)
It worked for some of the data frames, but I would get this exception with some data frames:
它适用于一些数据框,但我会得到一些数据框的异常:
raise Exception('Reindexing only valid with uniquely valued Index '
Exception: Reindexing only valid with uniquely valued Index objects
Anyone can help me get passed this error that happens on some of the data frames?
任何人都可以帮助我通过某些数据帧上发生的错误?
采纳答案by Iliyan Bobev
Do you have repeating columns in the two DataFrames? If yes, try to resolve that to have unique column names in the two frames, and execute the reindex again.
两个 DataFrame 中有重复的列吗?如果是,请尝试将其解析为在两个帧中具有唯一的列名,然后再次执行重新索引。

