在python中使用嵌套字典中的多个值迭代多行以更新数据帧



我创建了一个嵌套字典,为每个组合保留多个值,字典中的示例行如下:-

dict = {'A': {B: array([1,2,3,4,5,6,7,8,9,10]), C: array([array([1,2,3,4,5,6,7,8,9,10],...}}

有多个a,每个数组有多个数组。现在我想更新数据帧,它有以下几行:

<表类> 坳1 Col 2 3上校坳4tbody><<tr>B210C310

编辑版本2:引用字典和选择字典索引val

你创建的字典很混乱。我假设你想引用它,就像我所展示的方式(而不是C中所示的数组的数组)。还假设BC是值,而不是变量BC

我创建了字典dct(dict在python中是一个保留词),使用不同的值来显示它选择的值而不是索引。

import pandas as pd
import numpy as np
dct = {'A': {'B': np.array([.2,.4,.6,.8,1.0,1.2,1.4,1.6,1.8,2.0]),
'C': np.array([.3,.6,.9,1.2,1.5,1.8,2.1,2.4,2.7,3.0])
}
}
c = ['Col 1','Col 2','Col 3','Col 4']
d = [['A','B',2,10], ['A','C',3,10]]
df = pd.DataFrame(d,columns=c)
#repeat the values as per times in Col 3. This will create dups in 1 and 2 
df = df.loc[df.index.repeat(df['Col 3'])]
#Now groupby Col 1 and Col 2 and count the number of times we have Col 3 value
#This will give you index to reference the dictionary
df['Col 5'] = (df.groupby(['Col 1','Col 2'])['Col 3'].transform('cumcount'))
#Using the cumcount as index, pick the value from dict using keys Col 1, Col 2 and index Col 5
df['Col 5'] = df.apply(lambda x: dct[x['Col 1']][x['Col 2']][x['Col 5']],axis=1)
print (df)

它的输出将是:

Col 1 Col 2  Col 3  Col 4  Col 5
0     A     B      2     10    0.2
0     A     B      2     10    0.4
1     A     C      3     10    0.3
1     A     C      3     10    0.6
1     A     C      3     10    0.9

如果你想用col5乘以col4值,这很简单。将公式更改为(将col4乘以字典值的结果):

df['Col 5'] = df.apply(lambda x: x['Col 4'] * dct[x['Col 1']][x['Col 2']][x['Col 5']],axis=1)

结果将是:

Col 1 Col 2  Col 3  Col 4  Col 5
0     A     B      2     10    2.0
0     A     B      2     10    4.0
1     A     C      3     10    3.0
1     A     C      3     10    6.0
1     A     C      3     10    9.0

编辑版本1:不引用字典

如果您只是希望Col 1Col 2的每组Col 5的增量为10,那么您可以这样做。

c = ['Col 1','Col 2','Col 3','Col 4']
d = [['A','B',2,10],
['A','C',3,10]]
import pandas as pd
df = pd.DataFrame(d,columns=c)
df = df.loc[df.index.repeat(df['Col 3'])]
df['Col 5'] = (df.groupby(['Col 1','Col 2'])['Col 3'].transform('cumcount')+1)*10
print (df)

它的输出将是:

Col 1 Col 2  Col 3  Col 4  Col 5
0     A     B      2     10     10
0     A     B      2     10     20
1     A     C      3     10     10
1     A     C      3     10     20
1     A     C      3     10     30

如果您希望col3的值为1,则:

df['Col 3'] = 1

这将导致:

Col 1 Col 2  Col 3  Col 4  Col 5
0     A     B      1     10     10
0     A     B      1     10     20
1     A     C      1     10     10
1     A     C      1     10     20
1     A     C      1     10     30

如果你需要它来引用字典,那么我需要修改代码。

最新更新