[英]how to add a value to the next cell with python pandas
我有一個我感興趣的表中的值“x”。我想首先找到值“x”在表中的位置,然后在“x”右側的單元格中添加一個字符串“s” (下一列但同一行)。
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
我認為語法是錯誤的,有人知道嗎? 謝謝
假設您的 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 '')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.