python - 将数组数据与子数组数据匹配

标签 python pandas dataframe numpy

我有一个长度为 6 行的子数组 itemdata。该数据最初是在主数组中找到的,但已重新格式化,因此每行有 1 个唯一的产品。

我的主数组 saledata 的长度为 4 行,看起来有点像这样:

            id    sub-array
        0   001   [{'type': 'line_items', 'id': '78', 'attributes': {'status': 'allocated', 'quantity': 1, 'various_other_data': 'etc'}}]
        1   002   [{'type': 'line_items', 'id': '80', 'attributes': {'status': 'allocated', 'quantity': 2, 'various_other_data': 'etc'}}]
        2   003   [{'type': 'line_items', 'id': '85', 'attributes': {'status': 'allocated', 'quantity': 1, 'various_other_data': 'etc'}}, {'type': 'line_items', 'id': '86', 'attributes': {'status': 'allocated', 'quantity': 1, 'various_other_data': 'etc'}}]
        3   004   [{'type': 'line_items', 'id': '92', 'attributes': {'status': 'allocated', 'quantity': 2, 'various_other_data': 'etc'}}, {'type': 'line_items', 'id': '93', 'attributes': {'status': 'allocated', 'quantity': 2, 'various_other_data': 'etc'}}]

然后我有子数组itemdata(基本上只是json标准化列子数组):

    type        id   attributes.status   attributes.quantity    attributes.various_other_data
0   line_item   78   allocated           1                      etc
0   line_item   80   allocated           2                      etc
0   line_item   85   allocated           1                      etc
1   line_item   86   allocated           1                      etc
0   line_item   92   allocated           2                      etc
1   line_item   93   allocated           2                      etc

目前,我将子数组视为字符串(在对第二个数据帧进行 json 规范化之后),这允许我执行此操作:

for f in itemdata['id']:
    df['sub-array'].str.contains(f)

这会产生以下结果:

0     True
1    False
2    False
3    False
Name: relationships.line_items.data, dtype: bool
0    False
1     True
2    False
3    False
Name: relationships.line_items.data, dtype: bool
0    False
1    False
2     True
3    False
Name: relationships.line_items.data, dtype: bool
0    False
1    False
2     True
3    False
Name: relationships.line_items.data, dtype: bool
0    False
1    False
2    False
3     True
Name: relationships.line_items.data, dtype: bool
0    False
1    False
2    False
3     True
Name: relationships.line_items.data, dtype: bool

这一切都是正确的!但现在我试图将子数组与父数组匹配,将上述结果的索引与初始数组 saledata 匹配,其中 True 但正在努力找到正确的方法来执行此操作。

Python 似乎不喜欢下面的方法(系列的真值不明确 yada yada yada)并且不确定如何继续。

for f in itemdata['id']:
    if df['sub-array'].str.contains(f) == True:

非常感谢任何建议!

编辑:

这就是我正在寻找的(请注意,等等都已关闭并且不确定 pandas 将允许多行具有相同的索引值 - 如果不是的话,这不是一个大问题):

         id   type         itemdata.id   itemdata.attributes.status   itemdata.attributes.quantity
    0   001   line_items   78            allocated              etc
    1   002   line_items   80            allocated              etc
    2   003   line_items   85            allocated              etc
    2   003   line_items   86            allocated              etc
    3   004   line_items   92            allocated              etc
    3   004   line_items   93            allocated              etc

最佳答案

您可以使用DataFrame.join如果需要在按 Series.explode 分解的行设置索引标准化 子数组 后附加 id (或多列) :

import ast

df['sub-array'] = df['sub-array'].apply(ast.literal_eval)

s = df['sub-array'].explode()

cols = ['id']
df = df[cols].add_suffix('_parent').join(pd.json_normalize(s).set_index(s.index))
print (df)
  id_parent        type  id attributes.status  attributes.quantity  \
0       001  line_items  78         allocated                    1   
1       002  line_items  80         allocated                    2   
2       003  line_items  85         allocated                    1   
2       003  line_items  86         allocated                    1   
3       004  line_items  92         allocated                    2   
3       004  line_items  93         allocated                    2   

  attributes.various_other_data  
0                           etc  
1                           etc  
2                           etc  
2                           etc  
3                           etc  
3                           etc  

如果只需要处理id列并且id值是唯一的,则创建助手系列并使用Series.map :

s = df.set_index('id')['sub-array'].apply(ast.literal_eval).explode().str.get('id')
df['id_parent'] = df['id'].map(s)

关于python - 将数组数据与子数组数据匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76437569/

相关文章:

python - 如何有效地 vstack 一系列大型 numpy 数组 block ?

python - SciPy.sparse 迭代求解器 : No sparse right hand side support?

python - 如何过滤阅读超过4本书的用户?

python - 计算 Pandas 每周的变化(使用 groupby)?

python - 按 Pandas 列总和的值分组

api - 如何阻止 Python 中的 Keyerror 再次发生或创建异常来处理它?

r - 将 data.frame 拆分为矩阵并将对角线元素相乘以生成新列

Python:按名称加载模块

python - scikit-learn 中的 load_files 未加载目录中的所有文件

python - 通过索引/列元素连接数据帧