我正在嘗試轉(zhuǎn)換一個矩陣(df),所以我得到另一個(df2),并且不知道如何......[df] X Y Za None x Noneb None None xc x None None[df2] X Y Z None a None None None b c None None如果有幫助,這里是 df 的構(gòu)造:import pandas as pddf = pd.DataFrame([[None, 'x', None], [None, None, 'x'], ['x', None, None]], index=['a', 'b', 'c'], columns=['X', 'Y', 'Z'])print(f'\n{df.to_string()}')
3 回答
至尊寶的傳說
TA貢獻1789條經(jīng)驗 獲得超10個贊
您可以使用mask:
df = df.mask(df.notnull(), df.index)
print(df)
X Y Z
a None a None
b None None b
c c None None
忽然笑
TA貢獻1806條經(jīng)驗 獲得超5個贊
另一種使用方法apply:
ddf = df.apply(lambda row : pd.Series(row.name if el == 'x' else el for el in row), axis=1)
ddf.columns = df.columns
最后一行因為列名丟失了,所以你需要重新評估它們。
基本上是用'x'行索引替換所有值,保留其他值(即使它們不是None)。
結(jié)果ddf是:
X Y Z
a None a None
b None None b
c c None None
添加回答
舉報
0/150
提交
取消
