Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

pandas - In python how would you create two columns that iterate into eachother?

The question translate into this I have a simple dataframe lets call it df

id  k   t
2A  1   100
2A  2   100
2A  NaN 100
4C  3   80
4C  4   80
4C  1   80
3B  NaN 120
3B  7   120
3B  4   120

And I want to create a new column that is called t and t1. t1 is based on t and k and id. In this scenario I have only 3 Id's 2A, 4C and 3B. The final output will be.

id  k   t   t1
2A  1   100 99
2A  2   99  97
2A  NaN 97  97
4C  3   80  77
4C  4   77  73
4C  1   73  72
3B  NaN 120 120
3B  7   120 113
3B  4   113 109

So the idea is as follows

enter image description here

in Which t1 is simply

df['t1']=df['t']-df['k']

The conversion of values on t in the final df is the one that I don't know how to do because the first value of every id has to be based on the originals df["t"], but afterwards on df[t1] as the picture shows.

question from:https://stackoverflow.com/questions/65829898/in-python-how-would-you-create-two-columns-that-iterate-into-eachother

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let us try cumsum with groupby

df['t1'] = df.t-df.fillna(0).groupby('id').k.cumsum()
df['t'] = df['t1'] + df['k'].fillna(0)
df
Out[85]: 
   id    k      t     t1
0  2A  1.0  100.0   99.0
1  2A  2.0   99.0   97.0
2  2A  NaN   97.0   97.0
3  4C  3.0   80.0   77.0
4  4C  4.0   77.0   73.0
5  4C  1.0   73.0   72.0
6  3B  NaN  120.0  120.0
7  3B  7.0  120.0  113.0
8  3B  4.0  113.0  109.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...