使用字典作为键来划分两个Pandas DataFrame

时间:2016-11-30 15:26:01

标签: python pandas dictionary key division

我有一个DataFrame df1

 df1 = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))

df1.head()
   A  B  C  D
0  9  8  1  1
1  9  7  1  6
2  0  6  7  5
3  5  1  6  0
4  4  0  5  4

第二个DataFrame df2

  df2 = pd.DataFrame(np.random.randint(0,10,size=(10, 3)), columns=list('FGH'))

df2.head()
   F  G  H
0  8  5  9
1  3  0  7
2  2  5  4
3  3  5  4
4  5  6  6

字典词典:

dict = {"A" : "F", "B" : "F", "C" : "H", "D" : "G" }

我想使用字典的元素作为关键字来划分两个数据帧:列A列F列,列B列F列,列C列H列和列D列G列。结果应为:< / p>

df3.head

0 1.125 1.000 0.111 0.200
1 3.000 2.333 1.429 NA
...     

感谢。

2 个答案:

答案 0 :(得分:2)

您只需将/运算符直接用于Columns或DataFrame Series。

df3 = pd.DataFrame() #initialize an empty dataframe
for i in dict:
    df3[i+"/"+dict[i]] = df1[i]/df2[dict[i]]


df3.head()

enter image description here

答案 1 :(得分:2)

迭代字典中的项目,并将构成AttributeError: 'Standard' object has no attribute 'variable2' 中列名称的键与值(df1的列名)分开。它们形成一个系列对象,其名称对应于键。沿着圆柱方向连接这些。

最后,根据df2的列reindex来保留排序。

df1

enter image description here

注意: 我已经更改了字典的名称,因为不建议使用df = pd.concat([pd.Series(df1[k]/df2[v], name=k) for k,v in my_dict.items()], axis=1) df.reindex(columns=df1.columns) 来命名它们,这也是对应的内置-in类型的方式。