![](/img/trans.png)
[英]Combining data from different rows based on the cell content and creating new columns based on the cell values with pandas and python
[英]python (pandas) creating a new column based on values from different rows
我有一個來自 cvs 文件的數據框,如下所示:
#F E G
0 1 n.e. 153
1 1 60 15
2 1 99 10
3 1 S 23
4 2 n.e. 190
5 2 60 44
6 2 99 22
7 2 S 67
我想為此添加一個新列。
對於每個 [#F] 組,每行中的 [G] 值應除以行中的 [G] 值,其中 [E]='ne' 因此,最終應如下所示:
#F E G rel
0 1 n.e. 153 1.000
1 1 60 15 0.098
2 1 99 10 0.065
3 1 S 23 0.150
4 2 n.e. 190 1.000
5 2 60 44 0.232
6 2 99 22 0.116
7 2 S 67 0.353
我已經嘗試了幾種使用函數、組或 np.where 的方法,但問題比我的經驗要復雜一些,最終沒有任何效果。
謝謝你的幫助。
IIUC transform
df['Rel']=df.G/df.groupby(['name','#F']).G.transform('max')
df
name #F E G Rel
0 T.w. 1 n.e. 153 1.000000
1 T.w. 1 60 15 0.098039
2 T.w. 1 99 10 0.065359
3 T.w. 1 S 23 0.150327
4 T.w. 2 n.e. 190 1.000000
5 T.w. 2 60 44 0.231579
6 T.w. 2 99 22 0.115789
7 T.w. 2 S 67 0.352632
方法二
s=df.loc[df.E.eq('n.e.')].set_index(['name', '#F']).G.reindex(pd.MultiIndex.from_frame(df[['name', '#F']])).values
df['Rel']=df.G/s
或者
df['Rel']=df.G/df.G.mul(df.E.eq('n.e.')).groupby([df['name'],df['#F']]).transform('max')
df
name #F E G Rel
0 T.w. 1 n.e. 153 1.000000
1 T.w. 1 60 15 0.098039
2 T.w. 1 99 10 0.065359
3 T.w. 1 S 23 0.150327
4 T.w. 2 n.e. 190 1.000000
5 T.w. 2 60 44 0.231579
6 T.w. 2 99 22 0.115789
7 T.w. 2 S 67 0.352632
df.loc[df['E'] == 'n.e.', 'G_ne'] = df['G']
df['G_ne'] = df['G_ne'].fillna(method='ffill')
df['rel'] = df['G'] / df['G_ne']
print(df)
輸出:
#F E G G_ne rel
0 1 n.e. 153 153.0 1.000000
1 1 60 15 153.0 0.098039
2 1 99 10 153.0 0.065359
3 1 S 23 153.0 0.150327
4 2 n.e. 190 190.0 1.000000
5 2 60 44 190.0 0.231579
6 2 99 22 190.0 0.115789
7 2 S 67 190.0 0.352632
我會使用Series.div
。 使用Series.where
和Groupby.transform
為每個組創建一個具有相應ne
值的系列。
請注意,
first
,省略NaN
值,因此.ne.
的位置.ne.
在組中的價值並不重要。 我們也可以使用max
代替first
。
df['Rel']=df['G'].div(df['G'].where(df['E'].eq('n.e.'))
.groupby(df['#F']).transform('first'))
print(df)
#F E G Rel
0 1 n.e. 153 1.000000
1 1 60 15 0.098039
2 1 99 10 0.065359
3 1 S 23 0.150327
4 2 n.e. 190 1.000000
5 2 60 44 0.231579
6 2 99 22 0.115789
7 2 S 67 0.352632
編輯
df['Rel']=df['G'].div(df['G'].where(df['E'].eq('n.e. '))
.groupby(df['#F']).transform('first'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.