简体   繁体   English

Python pandas 如何用这些相同的值替换值之间的列中的零

[英]Python pandas how to replace zeros in a column between values with these same values

I have a csv file in which such a column is calculated:我有一个 csv 文件,其中计算了这样的列:

Combined
0
0
1
0
0
0
2
0
0
0
3
0
0
0
0
-1
0
0
0
0
-2
0
0
0
0
-3
0
0
0
1

I would like to change the values in it so that when, for example, the value -1 appears, all zeros up to the value -2 turn into -1, which would turn out something like this我想更改其中的值,例如,当值 -1 出现时,值 -2 之前的所有零都变成 -1,结果是这样的

Combined
0
0
1
1
1
1
2
2
2
2
3
3
3
3
3
-1
-1
-1
-1
-1
-2
-2
-2
-2
-2
-3
-3
-3
-3
1

I combine it into class functions in this way像这样把class功能组合起来

cols = ['Answers', 'step', 'step2']
        df['combined'] = df[cols].apply(lambda row: ''.join(row.values.astype(str)), axis=1)
        df['combined'] = df['combined'].str.replace('0.000', 'O',regex=True)
        df['combined'] = df['combined'].map(lambda x: x.lstrip('0.0').rstrip('.000'))
        df['combined'] = df['combined'].str.replace('O', '0')

For the sake of explanation, At the beginning of this csv there is always a pair of zeros, but after them either -1 or 1 always comes and then it always goes depending on the first number either -2 or 2 and the three comes exactly the same depending on the second number either -3 or 3 And after its cycle repeats and also depending on the three.为了解释起见,在此 csv 的开头总是有一对零,但在它们之后总是出现 -1 或 1,然后它总是取决于第一个数字 -2 或 2,而三个正好出现相同取决于第二个数字 -3 或 3 并且在其循环重复之后也取决于三个。 either -1 or 1. -1 或 1。

If need forward filling 0 to previous non 0 values use:如果需要将0向前填充到以前的非0值,请使用:

df['Combined'] = df['Combined'].replace(0, np.nan).ffill().fillna(0).astype(int)
print (df)
   Combined
0         0
1         0
2         1
3         1
4         1
5         1
6         2
7         2
8         2
9         2
10        3
11        3
12        3
13        3
14        3
15       -1
16       -1
17       -1
18       -1
19       -1
20       -2
21       -2
22       -2
23       -2
24       -2
25       -3
26       -3
27       -3
28       -3
29        1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM