根据其他数据框中的索引列表从其他数据框中向数据框中添加新列

phi*_*thy 4 python dataframe pandas

我有两个数据帧,数据帧中的每一行A都有一个索引列表,这些索引对应于数据帧中的条目B以及一组其他值。我想以某种方式加入两个数据帧,以使in中的每个条目都B具有其他值,A其中in 的索引位于in 中的索引B列表中A

到目前为止,我已经找到了一种提取该行中B每一行的索引列表的行的方法,A但是只能从该答案逐行进行,但是然后我不确定从何处去?另外,由于索引列表的大小会发生变化,因此不确定是否有更好的方法可以动态地对Pandas进行操作。

import pandas as pd
import numpy as np

# Inputs
A = pd.DataFrame.from_dict({
    "indices": [[0,1],[2,3],[4,5]],
    "a1": ["a","b","c"],
    "a2": [100,200,300]
})

print(A)
>>    indices a1   a2
>> 0  [0, 1]  a  100
>> 1  [2, 3]  b  200
>> 2  [4, 5]  c  300

B = pd.DataFrame.from_dict({
    "b": [10,20,30,40,50,60]
})

print(B)
>>     b
>> 0  10
>> 1  20
>> 2  30
>> 3  40
>> 4  50
>> 5  60

# This is the desired output
out = pd.DataFrame.from_dict({
    "b": [10,20,30,40,50,60],
    "a1": ["a","a", "b", "b", "c", "c"],
    "a2": [100,100,200,200,300,300]
})

print(out)
>>      b a1   a2
>> 0  10  a  100
>> 1  20  a  100
>> 2  30  b  200
>> 3  40  b  200
>> 4  50  c  300
>> 5  60  c  300

Run Code Online (Sandbox Code Playgroud)

Ank*_*nha 5

如果您的熊猫> = 0.25,则可以使用explode

C = A.explode('indices')
Run Code Online (Sandbox Code Playgroud)

这给出:

  indices a1   a2
0       0  a  100
0       1  a  100
1       2  b  200
1       3  b  200
2       4  c  300
2       5  c  300
Run Code Online (Sandbox Code Playgroud)

然后做:

output = pd.merge(B, C, left_index = True, right_on = 'indices')
output.index = output.indices.values    
output.drop('indices', axis = 1, inplace = True)
Run Code Online (Sandbox Code Playgroud)

最终输出:

    b a1   a2
0  10  a  100
1  20  a  100
2  30  b  200
3  40  b  200
4  50  c  300
5  60  c  300
Run Code Online (Sandbox Code Playgroud)