我有一个价值' x'从我感兴趣的表中。我想首先找到值' x'在表格中,并添加一个字符串' s到x'(下一列但同一行)右侧的单元格。
df[df.ix('x')] = s #would replace 'x' with 's'
df[df.ix('x')+1] = s #so i tried it with '+1' to indicate the same row but next the column but the syntax is wrong.
更新
示例原始表数据 -
columnA columnB
A
B
X
C
X
D
期望的结果 -
columnA columnB
A
X S
X S
B
X S
C
我的代码是简化版:
data = pd.read_excel('C:/Users/....table.xlsx', sep='\t')
for vh in data["columnA"]:
data[df.ix('X')+1] = s
#obviously the '+1' syntax is wrong, how should i change it?
#i want S in columnB where there is X in column A
提前谢谢!
更新新代码:
for line in f:
for vh in data["columnA"]:
vh = vh.rstrip()
tmp = data[line in vh]
tmp = tmp[list(tmp.columns[-1]) + tmp.columns.tolist()[:-1]]
tmp.columns = data.columns
data[tmp] = string
我认为语法错误,任何人都有任何想法? 谢谢
答案 0 :(得分:1)
假设您的DataFrame的最后一列中没有'x'
值:
tmp = df == 'X' # boolean mask
tmp = tmp[list(tmp.columns[-1]) + tmp.columns.tolist()[:-1]] # shift the order of columns to 1 ahead
tmp.columns = df.columns # restore names order in the mask
df[tmp] = 'S' # setting the s value to the cell right after the 'X'
对于你的两列DataFrame,它就像那样简单:
df["columnB"] = df["columnA"].apply(lambda x: 'S' if x == 'X' else '')