我有一個熊貓資料框,我需要用嵌套字典中的相應數字替換所有“是”值。嵌套字典由“Store”列的行值作為外部鍵組成。內部鍵是名為“A”和“B”的列。
這是資料框:
import pandas as pd
data = [['abc', 'jan','yes','no'], ['abc', 'feb','no','yes'], ['def', 'jan', 'yes','yes'], ['def', 'feb', 'no','yes']]
df = pd.DataFrame(data, columns = ['Store', 'Month', 'A','B' ])
df
Store Month A B
0 abc jan yes no
1 abc feb no yes
2 def jan yes yes
3 def feb no yes
這是嵌套字典:
# dict = {row value in 'Store' column:{column:point value}}
dict = {'abc':{'A':5,'B':4},'def':{'A':3,'B':2}}
這是所需的輸出:
Store Month A B
0 abc jan 5 no
1 abc feb no 4
2 def jan 3 2
3 def feb no 2
uj5u.com熱心網友回復:
替換'yes'為嵌套字典的值np.nan:fillna
d = {'abc':{'A':5,'B':4},'def':{'A':3,'B':2}}
out = df.replace({'yes': np.nan}).groupby('Store') \
.apply(lambda x: x.fillna(d[x.name])).droplevel(0)
print(out)
# Output
Store Month A B
0 abc jan 5 no
1 abc feb no 4
2 def jan 3 2
3 def feb no 2
uj5u.com熱心網友回復:
試試這個:
def find_num(store, col_value, col_name):
if col_value == "yes":
sub_dict = dict[store]
return sub_dict[col_name]
else:
return "no"
for col in list(df.columns):
if col == "Store" or col == "Month":
continue
df[col] = df.apply(lambda x: find_num(x['Store'], x[col], col), axis=1)
print(df)
uj5u.com熱心網友回復:
這是另一個使用np.where.
(i) map dict(僅供參考,dict是字典建構式的名稱,我將其替換為dct此處)到“存盤”以匹配每一行的相關字典。
(ii) 展平df[['A','B']]為一個 numpy 陣列
(iii) 迭代 (i) 的結果并獲取每個字典的值,并使用扁平化結果串列 itertools.chain
(iv) 用于np.where根據 (ii) 的結果是否為“是”來選擇值
(v) 將 (iv) 的結果重新整形為二維陣列并分配回 df[['A','B']]
from itertools import chain
mapper = df['Store'].map(dct)
flat_AB = df[['A','B']].to_numpy().flatten()
values_from_dict = list(chain.from_iterable([d.values() for d in mapper]))
df[['A','B']] = np.where(flat_AB == 'yes', values_from_dict, flat_AB).reshape(-1,2)
或者您可以直接使用DataFrame本身(但我認為這比上述方法慢)
df[['A','B']] = np.where(df[['A','B']] == 'yes', pd.DataFrame(df['Store'].map(dct).tolist()), df[['A','B']])
輸出:
Store Month A B
0 abc jan 5 no
1 abc feb no 4
2 def jan 3 2
3 def feb no 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417543.html
標籤:
上一篇:按位元組拆分字典
