如果我們有一個 pandas 資料框和一個用于資料框中值的映射字典,則可以使用字典作為映射替換資料框中的值,如下所示:
In: df
Out:
Col1 Col2
0 a c
1 b c
2 b c
In: key
Out: {'a': 1, 'b': 2, 'c': 3}
In: df.replace(key)
Out:
Col1 Col2
0 1 3
1 2 3
2 2 3
當映射字典將串列作為值時,如何完成類似的轉換?例如:
In: key
Out: {'a': [1, 0, 0], 'b': [0, 1, 0], 'c': [0, 0, 1]}
In: df.replace(key)
ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 1 output values where the mask is true
在此示例中,最終目標是擁有一個具有 3 行和 6 列的新資料框:
1 0 0 0 0 1
0 1 0 0 0 1
0 1 0 0 0 1
uj5u.com熱心網友回復:
IIUC,你可以applymap explode重塑:
df2 = df.applymap(key.get).explode(list(df.columns))
df2 = (df2
.set_index(df2.groupby(level=0).cumcount(), append=True)
.unstack(level=1)
)
輸出:
Col1 Col2
0 1 2 0 1 2
0 1 0 0 0 0 1
1 0 1 0 0 0 1
2 0 1 0 0 0 1
注意。重置列:df2.columns = range(df2.shape[1])
0 1 2 3 4 5
0 1 0 0 0 0 1
1 0 1 0 0 0 1
2 0 1 0 0 0 1
uj5u.com熱心網友回復:
您可以使用組合DataFrame.apply并Series.map執行此替換。從那里,您可以執行 aDataFrame.sum來連接串列,然后將資料轉換回新的DataFrame
out = pd.DataFrame(
df.apply(lambda s: s.map(key)).sum(axis=1).tolist()
)
print(out)
0 1 2 3 4 5
0 1 0 0 0 0 1
1 0 1 0 0 0 1
2 0 1 0 0 0 1
uj5u.com熱心網友回復:
嗯,這很棘手。
我想出的一種解決方案是在替換串列之前將串列轉換為它們的字串表示形式,因為 pandas 對lists 有特殊處理。然后您可以itertools.chain.from_iterable在每一行上使用將所有串列組合成一個大串列,并從中創建一個資料框:
import ast
from itertools import chain
n = df.replace({k: str(v) for k, v in key.items()}).applymap(ast.literal_eval)
df =pd.DataFrame(n.apply(lambda x: list(chain.from_iterable(x)), axis=1).tolist())
輸出:
>>> df
0 1 2 3 4 5
0 1 0 0 0 0 1
1 0 1 0 0 0 1
2 0 1 0 0 0 1
uj5u.com熱心網友回復:
這是一種用串列替換專案而不回圈或字串化的方法:
df[:] = pd.Series(key)[df.to_numpy().flatten()].to_numpy().reshape(df.shape)
輸出:
>>> df
Col1 Col2
0 [1, 0, 0] [0, 0, 1]
1 [0, 1, 0] [0, 0, 1]
2 [0, 1, 0] [0, 0, 1]
或者,您可以使用explodeandreshape將資料直接轉換為 numpy 陣列:
arr = pd.Series(key)[df.to_numpy().flatten()].explode().to_numpy().reshape(-1, 6) # 6 = len of one of the items of `key` * number of columns in df
輸出:
>>> arr
array([[1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 1]], dtype=object)
>>> pd.DataFrame(arr)
0 1 2 3 4 5
0 1 0 0 0 0 1
1 0 1 0 0 0 1
2 0 1 0 0 0 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/445124.html
