Python 如何在dataframe上迭代以将字典解压到新的dataframe中

Python 如何在dataframe上迭代以将字典解压到新的dataframe中,python,pandas,Python,Pandas,我想解包一个数据帧,其中包含嵌套在每列字典中的可变数量的“ProductID”。 示例表: awardedProducts 0 [] 1 [{'productID': 14306}] 2 [] 3 [] 4 [] 5 [] 6 [] 7 [{'productID': 60974}, {'productID': 72961}] 8 [{'productID': 78818}, {'productID': 86765}] 9 [{'productID': 15

我想解包一个数据帧,其中包含嵌套在每列字典中的可变数量的“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全部列出的系列。 例如:

因为,您可以这样做:

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上分享新版本pandas的
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

为那些不想更新的人共享

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


如果我可以问一下的话,您是如何获得数据帧的?它来自我的ERP API。我查询活动促销,并且包含在促销中的产品是嵌套的。我需要将它们转换为更简单的格式,以便与新促销项目列表进行比较,以检查是否已经列出了其中的任何项目。您能否在提供输入的情况下显示所需输出的示例?仅供参考,我询问的原因是数据框的数据看起来并不理想。但是如果它来自一个API,那么您可能对此无能为力。另一个问题是
[{'productID':14306}]
字典列表吗?这很好,但我需要先更新我的熊猫。我将在以后执行此操作。@我个人不喜欢apply pd。Serise方法,如果您不想更新熊猫,请检查,我会更新
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')