如何遍历数据框以将字典解包到新数据框

2024-03-28 22:41:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解包一个数据帧,它包含嵌套在每列字典中的可变数量的“productId”。 示例表:

awardedProducts
0   []
1   [{'productID': 14306}]
2   []
3   []
4   []
5   []
6   []
7   [{'productID': 60974}, {'productID': 72961}]
8   [{'productID': 78818}, {'productID': 86765}]
9   [{'productID': 155707}]
10  [{'productID': 54405}, {'productID': 69562}, {...

我试着用

df = []
for row, index in activeTitles.iterrows():
    df.append(index[0])

我希望最终得到一个单列数据帧,或者productid全部列出的系列。 例如:

productID
0  14306
1  60974
2  72961
3  78818
4  86765
5  155707
6  54405
7  69562

Tags: 数据in示例dffor数量index字典
2条回答

因为there is no flatmap operation in Pandas,您可以这样做:

import pandas as pd

data = pd.Series([[], [{'productID': 14306}], [], [], [], [], [],
                  [{'productID': 60974}, {'productID': 72961}],
                  [{'productID': 78818}, {'productID': 86765}],
                  [{'productID': 155707}], [{'productID': 54405}, {'productID': 69562}]])
products = (data.apply(pd.Series).unstack().dropna()
            .apply(lambda p: p['productID']).reset_index(drop=True))
print(products)
# 0     14306
# 1     60974
# 2     72961
# 3     78818
# 4     86765
# 5    155707
# 6     54405
# 7     69562
# dtype: int64

很高兴在0.25.0上分享熊猫的新版本explode

s=data.explode().str.get('productID').dropna()
s
Out[91]: 
1      14306.0
7      60974.0
7      72961.0
8      78818.0
8      86765.0
9     155707.0
10     54405.0
10     69562.0
dtype: float64

为那些不想更新pandas的人共享function

unnesting(data.to_frame('pid'),['pid'],1)['pid'].str.get('productID').dropna()
Out[18]: 
1      14306
7      60974
7      72961
8      78818
8      86765
9     155707
10     54405
10     69562
Name: pid, dtype: int64

def unnesting(df, explode, axis):
    if axis==1:
        idx = df.index.repeat(df[explode[0]].str.len())
        df1 = pd.concat([
            pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
        df1.index = idx
        return df1.join(df.drop(explode, 1), how='left')
    else :
        df1 = pd.concat([
                         pd.DataFrame(df[x].tolist(), index=df.index).add_prefix(x) for x in explode], axis=1)
        return df1.join(df.drop(explode, 1), how='left')

相关问题 更多 >