English 中文(简体)
替换数据栏中最后出现的数值
原标题:Replace the last occurrence of a value in a column of a DataFrame

我有以下数据框架:

data1 = [[2,5,6,3,1],
         [2,2,5,4,2],
         [0,1,2,2,3],
         [6,2,1,0,9],
         [2,3,4,1,2]]
df = pd.DataFrame(data1)
print(df)

I need to replace only the last occurrence of the value 2 in each column with the value 7. Note the replacement is ONLY for the last 2 , the proceeding 2 s in the column should remain in place. The desired result being:

[[2,5,6,3,1],
 [2,2,5,4,2],
 [0,1,7,7,3],
 [6,7,1,0,9],
 [7,3,4,1,7]]

I tried to use last_valid_index(), as well as diff(), and did not get the results I was looking for. Like the following:

cond = df.eq(2) & df.last_valid_index()==2
out = df.mask(cond, 7)
print(out)

我已尝试过这些版本以及<编码>diff(>>),我似乎无法取得预期结果(如上所示)。 任何建议都将受到高度赞赏。

问题回答

Try:

m = df.eq(2).replace(False, np.nan).bfill()
print(df.mask(m ^ m.shift(-1), 7))

印刷:

   col1  col2  col3  col4  col5
0     2     5     6     3     1
1     2     2     5     4     2
2     0     1     7     7     3
3     6     7     1     0     9
4     7     3     4     1     7

初始<代码>df:

   col1  col2  col3  col4  col5
0     2     5     6     3     1
1     2     2     5     4     2
2     0     1     2     2     3
3     6     2     1     0     9
4     2     3     4     1     2

解释:

m = df.eq(2).replace(False, np.nan).bfill()
print(m)

   col1  col2  col3  col4  col5
0  True  True  True  True  True
1  True  True  True  True  True
2  True  True  True  True  True
3  True  True   NaN   NaN  True
4  True   NaN   NaN   NaN  True

print(m.shift(-1))

   col1  col2  col3  col4  col5
0  True  True  True  True  True
1  True  True  True  True  True
2  True  True   NaN   NaN  True
3  True   NaN   NaN   NaN  True
4   NaN  None  None  None   NaN

# The ^ (XOR) operation is True if there is only one value True

print(m ^ m.shift(-1))

    col1   col2   col3   col4   col5
0  False  False  False  False  False
1  False  False  False  False  False
2  False  False   True   True  False
3  False   True  False  False  False
4   True  False  False  False   True

# .mask() sets the True values to 7

另一种版本:

tmp = (df == 2)[::-1].idxmax()

for c, v in zip(tmp.index, tmp):
    df.loc[v, c] = 7

print(df)

idxmax(,以获取first到场>,因此,你只需要将数据范围放在工作上。

现在,你有指数的矢量,但数据框架并没有在轴线上形成支持指数,然而,NumPy阵列确实如此,因此,你可以通过。 但有一点:如果你的数据框架有一个非违约指数,那么你就不得不放弃。

df.values[df.reset_index(drop=True)[::-1].eq(2).idxmax(), range(len(df))] = 7
df

结果:

   0  1  2  3  4
0  2  5  6  3  1
1  2  2  5  4  2
2  0  1  7  7  3
3  6  7  1  0  9
4  7  3  4  1  7




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...