将字典值替换为数据框

时间:2018-06-28 07:32:03

标签: pandas

我的一侧有以下df

          ACCOR SA  ADMIRAL  ADECCO  BANKIA  BANKINTER
ADMIRAL         0        0       0       0          0
ADECCO          0        0       0       0          0
BANKIA          0        0       0       0          0

以及另一个dict

{'ADMIRAL': 1, 'ADECCO': -1, 'BANKIA': -1}

其中df.index的值对应于dict.keys

我想将dict.values替换为df,每行放置一个值以获得此输出:

          ACCOR SA  ADMIRAL  ADECCO  BANKIA  BANKINTER
ADMIRAL         0        1       0       0          0
ADECCO          0        0      -1       0          0
BANKIA          0        0       0      -1          0

1 个答案:

答案 0 :(得分:2)

按dict值循环并按at设置值:

d = {'ADMIRAL': 1, 'ADECCO': -1, 'BANKIA': -1}

for k, v in d.items():
    df.at[k, k] = v
    #alternative
    #df.loc[k, k] = v
print (df)
         ACCOR SA  ADMIRAL  ADECCO  BANKIA  BANKINTER
ADMIRAL         0        1       0       0          0
ADECCO          0        0      -1       0          0
BANKIA          0        0       0      -1          0

另一种解决方案是由DataFrameMultiIndex.from_arraysunstack创建dict

s = pd.Series(list(d.values()), index=pd.MultiIndex.from_arrays([d.keys(), d.keys()]))
df1 = s.unstack()
print (df1)
         ADECCO  ADMIRAL  BANKIA
ADECCO     -1.0      NaN     NaN
ADMIRAL     NaN      1.0     NaN
BANKIA      NaN      NaN    -1.0

然后将非NaN替换为combine_first

df = df1.combine_first(df)
print (df)
         ACCOR SA  ADECCO  ADMIRAL  BANKIA  BANKINTER
ADECCO        0.0    -1.0      0.0     0.0        0.0
ADMIRAL       0.0     0.0      1.0     0.0        0.0
BANKIA        0.0     0.0      0.0    -1.0        0.0