我有一个数据框(下面的屏幕截图),其中包含“月”列以及一些分类列和数字列。 类别列共同构成定义行的键。
我想调整一些数字,以便:
如果Obj_col3 == XY并且Month == 2018-12: 然后选择相应的Num_col3值并乘以2。
然后将此Num_col3 * 2分配给Num_col2,但是在月份为2018-04的行中,分类对象列具有与上面的步骤1中选择的组合或键相同的组合或键。
< / li>输出数据框:
答案 0 :(得分:2)
由DataFrame.set_index
在MultiIndex
和Obj_col1
组的列中创建Obj_col2
,然后按条件设置值,最后为原始索引设置reset_index
:
print (df)
Obj_col1 Obj_col2 Obj_col3 Num_col1 Num_col2 Num_col3 Month
0 A AB XY 74 40 97 2018-04
1 A AB XY 61 26 29 2018-12
2 A AB XY 50 75 92 2019-03
3 A AB XY 33 99 87 2019-04
4 B AB XY 74 40 7 2018-04
5 B AB XY 61 26 1 2018-12
6 B AB XY 50 75 9 2019-03
7 B AB XY 33 99 8 2019-04
8 C AB XA 74 40 9 2018-04
9 C AB XA 61 26 1 2018-12
10 C AB XA 50 75 92 2019-03
11 C AB XA 33 99 87 2019-04
df = df.set_index(['Obj_col1','Obj_col2'])
m1 = (df['Obj_col3'] == 'XY') & (df['Month'] == '2018-12')
m2 = (df['Obj_col3'] == 'XY') & (df['Month'] == '2018-04')
df.loc[m2, 'Num_col2'] = df.loc[m1, 'Num_col3'] * 1000 # * 2 in real data
df = df.reset_index()
print (df)
Obj_col1 Obj_col2 Obj_col3 Num_col1 Num_col2 Num_col3 Month
0 A AB XY 74 29000 97 2018-04
1 A AB XY 61 26 29 2018-12
2 A AB XY 50 75 92 2019-03
3 A AB XY 33 99 87 2019-04
4 B AB XY 74 1000 7 2018-04
5 B AB XY 61 26 1 2018-12
6 B AB XY 50 75 9 2019-03
7 B AB XY 33 99 8 2019-04
8 C AB XA 74 40 9 2018-04
9 C AB XA 61 26 1 2018-12
10 C AB XA 50 75 92 2019-03
11 C AB XA 33 99 87 2019-04
另一种带有迭代的解决方案,但是如果有大量的组,则在第一种解决方案中性能会更好:
def f(x):
m1 = (x['Obj_col3'] == 'XY') & (x['Month'] == '2018-12')
m2 = (x['Obj_col3'] == 'XY') & (x['Month'] == '2018-04')
x.loc[m2, 'Num_col2'] = (x.loc[m1, 'Num_col3'] * 1000).values
return x
df = df.groupby(['Obj_col1','Obj_col2']).apply(f)
答案 1 :(得分:1)
temp = pd.DataFrame({'objcol1': ['A', 'A', 'B', 'B'],
'objcol2': ['AB', 'AB', 'BC', 'BC'],
'objcol3': ['XY', 'XY', 'XY', 'XY'],
'numcol2': [40, 26, 96, 62],
'numcol3': [97, 29, 85, 11],
'month': pd.to_datetime(['2018-04', '2018-12', '2018-04', '2018-12'])})
# Create an index to iterative with
temp['key'] = temp['objcol1'] + temp['objcol2'] + temp['objcol3']
for k in temp['key'].tolist():
# make two conditions to index properly
condition_12 = (temp['key'] == k) & (temp['month'] == '2018-12-01')
condition_04 = (temp['key'] == k) & (temp['month'] == '2018-04-01')
# multiply and paste
temp.loc[condition_04, 'numcol2'] = temp.loc[condition_12, 'numcol3'].values[0] * 2