[英]Access rightmost two columns of pandas dataframe, by number
我希望在滿足條件時覆蓋df
一些值。 使用下面的df
,當col B
等於lst
值時,我想用X
替換col C,D
值。
這可以使用下面的方法來實現,但我希望使用索引來選擇最后兩列,而不是使用硬編碼標簽。
df = pd.DataFrame({
'A' : [1,1,1,1,1,1,1,1],
'B' : ['X','Foo','X','Cat','A','A','X','D'],
'C' : [1,1,1,1,1,1,1,1],
'D' : [1,1,1,1,1,1,1,1],
})
lst = ['Foo','Cat']
df.loc[df.B.isin(lst), ['C','D']] = 'X'
試圖:
df.loc[df.B.isin(lst), df.loc[:-2]] = 'X'
故意的:
A B C D
0 1 X 1 1
1 1 Foo X X
2 1 X 1 1
3 1 Cat X X
4 1 A 1 1
5 1 A 1 1
6 1 X 1 1
7 1 D 1 1
如果我理解了這個問題,看起來您正在搜索iloc
:
df.iloc[df.B.isin(lst).values, -2:] = 'X'
在大多數情況下, df.loc[df.B.isin(lst), -2:] = 'X'
也將返回相同的結果,但-2:
slice 的解釋會因列名稱為整數類型而有所不同.
這是我對 pandas-y 方法的最佳嘗試,下面是超級丑陋且性能較差的apply
方法:
import pandas as pd
df = pd.DataFrame({
'A' : [1,1,1,1,1,1,1,1],
'B' : ['X','Foo','X','Cat','A','A','X','D'],
'C' : [1,1,1,1,1,1,1,1],
'D' : [1,1,1,1,1,1,1,1],
})
# get working index once,
# where column "B" in lst,
# store
ind = df["B"].isin(lst)
# get working slice with index
df_slice = df[ind]
# set the "C" and "D" columns
df_slice["C"], df_slice["D"] = "X", "X"
# set the original df slice
# to our working slice
df[df.B.isin(lst)] = df_slice
print(df)
### PRINTS:
A B C D
0 1 X 1 1
1 1 Foo X X
2 1 X 1 1
3 1 Cat X X
4 1 A 1 1
5 1 A 1 1
6 1 X 1 1
7 1 D 1 1
這是逐行apply
方法。 這不是最漂亮的解決方案,但它完成了工作。 請注意,這只是用 Xs 替換了行的其余部分。
import pandas as pd
df = pd.DataFrame({
'A' : [1,1,1,1,1,1,1,1],
'B' : ['X','Foo','X','Cat','A','A','X','D'],
'C' : [1,1,1,1,1,1,1,1],
'D' : [1,1,1,1,1,1,1,1],
})
def apply_function(row):
lst = ['Foo','Cat']
return row if row["B"] not in lst else [
# first two rows
*row[:2],
# Xs for the rest of the row
*["X" for r in range(len(row) - 2)]
]
df = df.apply(apply_function, axis=1)
print(df)
### PRINTS:
A B C D
0 1 X 1 1
1 1 Foo X X
2 1 X 1 1
3 1 Cat X X
4 1 A 1 1
5 1 A 1 1
6 1 X 1 1
7 1 D 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.