在一个单元格中转换具有多个值的数据帧
我有一个如下所示的数据框
id value index
5eb3cbcc434474213e58b49a [1,2,3,4,6] [0,1,2,3,4]
5eb3f335434474213e58b49d [1,2,3,4] [0,2,3,4]
5eb3f853434474213e58b49f [1,2,3,4] [0,2,3,4]
5eb40395434474213e58b4a2 [1,2,3,4] [0,1,2,3]
5eb40425434474213e58b4a5 [1,2] [0,2]
我尝试在以下内容中转换此数据框,因为索引旨在作为每个单独值的标题,看起来像这样:
id 0 1 2 3 4
5eb3cbcc434474213e58b49a 1 2 3 4 6
5eb3f335434474213e58b49d 1 Nan 2 3 4
5eb3f853434474213e58b49f 1 Nan 2 3 4
5eb40395434474213e58b4a2 1 2 3 4 Nan
5eb40425434474213e58b4a5 1 Nan 2 Nan Nan
我尝试首先拆分列表列表:
new_df = pd.DataFrame(df.Value.str.split(',').tolist(), index=df.Index).stack()
new_df = new_df.reset_index([0, 'Index'])
new_df.columns = ['Value', 'Index']
但是我收到错误
类型错误:不可散列的类型:“列表”
是什么导致了这个错误?
回答
您可以.apply()与 一起使用pd.Series(),如下所示:
df = df.set_index('id').apply(lambda x: pd.Series(x['value'], index=x['index']), axis=1).reset_index()
print(df)
id 0 1 2 3 4
0 5eb3cbcc434474213e58b49a 1.0 2.0 3.0 4.0 6.0
1 5eb3f335434474213e58b49d 1.0 NaN 2.0 3.0 4.0
2 5eb3f853434474213e58b49f 1.0 NaN 2.0 3.0 4.0
3 5eb40395434474213e58b4a2 1.0 2.0 3.0 4.0 NaN
4 5eb40425434474213e58b4a5 1.0 NaN 2.0 NaN NaN
这利用了以下.apply()功能特性:
默认行为(无)取决于应用函数的返回值:类似列表的结果将作为一系列结果返回。但是,如果 apply 函数返回一个 Series 这些将扩展为 columns。
此功能有助于我们为需要将数据扩展到列同时将新列合并到现有数据中的问题提供一个简单的解决方案,方法是将现有行索引保留和分配给这些新列。我用它为一个经典问题提供了一个简单的答案:如何合并 Series 和 DataFrame。