简体   繁体   English

Dataframe.loc 返回字典或 Dataframe [已解决](无法处理非唯一的多索引!)

[英]Dataframe.loc returns dictionary or a Dataframe [Solved] (Cannot handle a non-unique multi-index!)

I had two dataframes that are being read from two almost identical.csv using pd.read_csv().我有两个数据帧正在使用 pd.read_csv() 从两个几乎相同的 .csv 中读取。

When I use.loc[index1] on one of them it returns a Dictionary such as: col1 val1 col2 val2 col3 val3 Name: (index1), dtype: object当我在其中一个上使用 .loc[index1] 时,它会返回一个字典,例如:col1 val1 col2 val2 col3 val3 Name: (index1), dtype: object

But with the other I've realized it actually returns a Dataframe. Some operations such as df1[col1] = df2[col2] + constant will through errors.但是对于另一个我已经意识到它实际上返回了 Dataframe。一些操作如df1[col1] = df2[col2] + constant将通过错误。

To make it even harder I'm actually using MultiIndex.为了让它更难,我实际上使用了 MultiIndex。 I'm getting this error: Cannot handle a non-unique multi-index!我收到此错误: Cannot handle a non-unique multi-index!

I've figured out that.loc returns a Dataframe or an Dictionary-like object depending on if there are duplicated indexes.我发现 .loc 返回一个 Dataframe 或一个类似字典的 object 取决于是否有重复的索引。 This condition is not explained in the pandas documentation or I've not find it. pandas 文档中没有解释这种情况,或者我没有找到它。

If the index are actually unique try using something along this code: df.reset_index().drop_duplicates(subset=["index1"]).set_index(["index1"]) or just df.drop_duplicates(subset=["index1"]) after reading the csv but before setting the index如果索引实际上是唯一的,请尝试使用以下代码: df.reset_index().drop_duplicates(subset=["index1"]).set_index(["index1"])df.drop_duplicates(subset=["index1"])在读取 csv 之后但在设置索引之前

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 非唯一索引上的 Dataframe.loc - Dataframe.loc on non-unique index 需要处理具有非唯一多索引的串联数据帧 - Need to handle a concatenated dataframe with non-unique multi-index ValueError:无法处理非唯一的多索引! 尝试将来自多个数据帧的列合并到一个 dataframe - ValueError: cannot handle a non-unique multi-index! When trying to combine columns from multiple dataframes in to one dataframe ValueError:无法处理非唯一的多索引。 添加列后使用 .loc 或 set_index 时 - ValueError: cannot handle a non-unique multi-index! when using .loc or .set_index after adding a column ValueError:无法处理非唯一的多索引! 即使我们有唯一索引 - ValueError: cannot handle a non-unique multi-index! even when we have unique index Pandas ValueError:尝试重新索引时无法处理非唯一多索引 - Pandas ValueError: cannot handle a non-unique multi-index when trying to re-index 带有CSS样式属性错误的Pandas数据框(非唯一多索引)到html表 - Pandas dataframe (non-unique multi-index) to html table with CSS styling attribute error pandas.concat:无法处理非唯一的多索引! 熊猫蟒 - pandas.concat: Cannot handle a non-unique multi-index! Pandas Python 这是什么意思? xarray 错误:无法处理非唯一的多索引 - what does this mean? xarray error: cannot handle a non-unique multi-index Pandas Dataframe .loc + 更新非唯一日期时间索引? - Pandas Dataframe .loc + update on a non-unique Datetime Index?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM