目录
1、 需要分别查看行索引和列索引网上很多方法是重置行索引,有可能还是无法解决问题,原因是可能是列索引存在重复的情况
2、重置行索引办法
df.reset_index(drop=True, inplace=True)
3、重置列索引方法df.columns查看重复的列,然后删除重复列即可
利用pandas的concat方法报错如下 :
Traceback (most recent call last): File "E:价格v1.1 .py", line 357, ingetAllProduct() File "E:价格v1.1 .py", line 120, in getAllProduct df3 = ji(hebing_df) File "E:价格v1.1 .py", line 157, in ji df2 = pd.concat(df_list) File "D:Python310libsite-packagespandasutil_decorators.py", line 311, in wrapper return func(*args, **kwargs) File "D:Python310libsite-packagespandascorereshapeconcat.py", line 360, in concat return op.get_result() File "D:Python310libsite-packagespandascorereshapeconcat.py", line 591, in get_result indexers[ax] = obj_labels.get_indexer(new_labels) File "D:Python310libsite-packagespandascoreindexesbase.py", line 3721, in get_indexer raise InvalidIndexError(self._requires_unique_msg) pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects
利用pandas的concat方法可以对多个DataFrame进行快捷的堆叠,非常方便,但是在使用concat会出现“pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects
”的提示,翻译过来就是:使用pandas对df进行concat操作时,相应的行、列索引必须唯一
问题原因
索引由于特殊操作存在重复的情况
解决办法
1、 需要分别查看行索引和列索引
网上很多方法是重置行索引,有可能还是无法解决问题,原因是可能是列索引存在重复的情况、
2、重置行索引办法
df.reset_index(drop=True, inplace=True)
3、重置列索引方法
df.columns查看重复的列,然后删除重复列即可
import pandas as pd
df=pd.read_table(fname)
3、重置列索引方法
df.columns查看重复的列,然后删除重复列即可
import pandas as pd df=pd.read_table(fname)
列名为:
Time, Time Relative, N2, Time, Time Relative, H2, etc...
所有时间和时间相关列都包含相同的数据。我想要:
Time, Time Relative, N2, H2
我试图删除的所有尝试,如:
df=df.T.drop_duplicates().T
导致唯一值索引错误:
Reindexing only valid with uniquely valued index objects
解决:
df = df.loc[:,~df.columns.duplicated()]
工作原理:
假设数据帧的列是['alpha','beta','alpha']
df.columns.duplicated()为每列返回一个布尔数组:aTrue或False。如果是False,那么列名在这一点上是唯一的,如果是True,那么列名在前面是重复的。例如,使用给定的示例,返回值将是[False,False,True]。
Pandas允许使用布尔值进行索引,从而只选择True值。因为我们想保留未重叠的列,所以需要翻转上面的布尔数组(即[True, True, False] = ~[False,False,True])
最后,df.loc[:,[True,True,False]]使用上述索引功能只选择不重复的列。
注意:上面只检查列名称,不检查列值。



