Python 在数据框'中插入值;在右索引中添加新列
我想获得一些数据的下界,并将其插入相对索引的新列中。 例如:Python 在数据框'中插入值;在右索引中添加新列,python,pandas,dataframe,Python,Pandas,Dataframe,我想获得一些数据的下界,并将其插入相对索引的新列中。 例如: My df: col1 col2 0 1 3 1 2 4 2 5 8 3 1 2 4 8 4 5 6 2 6 4 8 7 8 6 8 6 4 9 5 9 lower_bound
My df:
col1 col2
0 1 3
1 2 4
2 5 8
3 1 2
4 8 4
5 6 2
6 4 8
7 8 6
8 6 4
9 5 9
lower_bound = 0.1
df['newcol']=df[(df.col1 == 8)].col2.quantile(lower_bound)
这是我的输出:
col1 col2 newcol
0 1 3 4.02
1 2 4 4.02
2 5 8 4.02
3 1 2 4.02
4 8 4 4.02
5 6 2 4.02
6 4 8 4.02
7 8 6 4.02
8 6 4 4.02
9 5 9 4.02
但我想获得:
col1 col2 newcol
0 1 3
1 2 4
2 5 8
3 1 2
4 8 4 4.02
5 6 2
6 4 8
7 8 6 4.02
8 6 4
9 5 9
提前非常感谢 将输出分配给筛选后的新列:
lower_bound = 0.1
m = df.col1 == 8
df.loc[m, 'newcol'] = df.loc[m, 'col2'].quantile(lower_bound)
#another solution
#df['newcol'] = np.where(m, df.loc[m, 'col2'].quantile(lower_bound), np.nan)
print (df)
0 1 3 NaN
1 2 4 NaN
2 5 8 NaN
3 1 2 NaN
4 8 4 4.2
5 6 2 NaN
6 4 8 NaN
7 8 6 4.2
8 6 4 NaN
9 5 9 NaN
还包括:
In [728]: val = df[(df.col1 == 8)].col2.quantile(lower_bound)
In [741]: val
Out[741]: 4.2
In [745]: df.loc[(df.col1 == 8),'newcol'] = val
In [746]: df
Out[746]:
col1 col2 newcol
0 1.0 3.0 NaN
1 2.0 4.0 NaN
2 5.0 8.0 NaN
3 1.0 2.0 NaN
4 8.0 4.0 4.2
5 6.0 2.0 NaN
6 4.0 8.0 NaN
7 8.0 6.0 4.2
8 6.0 4.0 NaN
9 5.0 9.0 NaN