我正在尝试处理以下错误:ValueError: cannot reindex from a duplicate axis
。
我的数据集看起来像
first_column second_column ... fifth_column ... eleventh_column ... Age
example 1 first ex ['avers','aaa','hello'] 41241 12
example 2 second ex [] 431 32
another third ex ['AA','B','C','aaa','hello'] 21 32
example 1 example ['avers','aaa','hello'] 41241 12
我想要这样的东西:
first_column second_column ... fifth_column ... eleventh_column ... Age
example 1 first ex avers 41241 12
example 1 first ex aaa 41241 12
example 1 first ex hello 41241 12
example 2 second ex nan 431 32
another third ex AA 21 32
another third ex B 21 32
another third ex C 21 32
another third ex aaa 21 32
another third ex hello 21 32
example 1 example avers 41241 12
example 1 example aaa 41241 12
example 1 example hello 41241 12
根据我的理解,我应该申请explode
:
df = df.loc[:,~df.columns.duplicated()]
df1=df.set_index('first_column').apply(pd.Series.explode).reset_index()
df1.fifth_column
但是,我得到了一个错误:
ValueError: cannot reindex from a duplicate axis.
我做错了什么
如果没有熊猫数据帧格式的数据,很难进行检查,但看起来您正在将explode应用于整个数据帧,而您应该只将其应用于
fifth_column
。您需要传递列名才能作为参数分解df.explode('fifth_column')
可能会出现在代码中的某个地方除非您完全确定,否则通常不建议使用具有重复值的索引(如
first_column
),因为某些操作可能不支持该索引由于看起来您正试图将索引重置为默认整数值,并仅使用
set_index()
删除df
的“剩余”索引值,因此我建议如下:df1 = df.apply(pd.Series.explode).set_index('first_column').reset_index()
相关问题 更多 >
编程相关推荐