我有以下資料集:
import pandas as pd
import numpy as np
d = {'column1': ['a', 'b', 'c'], 'va1': [10, 8, 6], 'va2': [1, 2, 3], 'vb1': [4, 2, 6], 'vb2': [1, 4, 8], 'vc1': [2, 6, 8], 'vc2': [2, 1, 8] }
data_frame = pd.DataFrame(data=d)
我想要做的是用 0 替換 column1 和其他列值重合的值。所需的資料集如下:
d1 = {'column1': ['a', 'b', 'c'], 'va1': [0, 8, 6], 'va2': [0, 2, 3], 'vb1': [4, 0, 6], 'vb2': [1, 0, 8], 'vc1': [2, 6, 0], 'vc2': [2, 1, 0] }
data_frame1 = pd.DataFrame(data=d1)
因為我的原始資料集很大,所以我想避免使用 groupby 和melt 命令。例如,一個建議是:將 column1 作為索引,重命名所有列并將 ij 元素替換為 0,其中列和索引匹配。以下是我的意思的起點:
data_frame.set_index('column1', inplace=True)
data_frame.columns=data_frame.columns.str[1:2] # Now column and index has the same strings
# Replace ij elements with 0 where index and column matches.
有什么建議嗎?
uj5u.com熱心網友回復:
使用 numpy 廣播將列的第二個值與索引值進行比較并設定0為DataFrame.mask:
data_frame.set_index('column1', inplace=True)
cols=data_frame.columns.str[1:2]
data_frame = data_frame.mask(data_frame.index.to_numpy()[:, None] == cols.to_numpy(), 0)
print (data_frame)
va1 va2 vb1 vb2 vc1 vc2
column1
a 0 0 4 1 2 2
b 8 2 0 0 6 1
c 6 3 6 8 0 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/380562.html
上一篇:如何根據值從串列中選擇r%樣本?
