我有一个通过调用Pandas.io.json.json_normalize()生成的DataFrame。这是一个
例:
dfIn = pd.DataFrame({'seed':[1324367672,1324367672,1324367673,1324367673,1324367674,1324367674], 'lanePolicy':[True,False,True,False,True,False,],
'stepsPerTrip':[40,37,93,72,23,70], 'density':[51,51,208,208,149,149]})
seed lanePolicy stepsPerTrip density
0 1324367672 True 40 51
1 1324367672 False 37 51
2 1324367673 True 93 208
3 1324367673 False 72 208
4 1324367674 True 23 149
5 1324367674 False 70 149
请注意,在
dfIn['seed']
中有成对的匹配值,在True
中有一个False
和一个dfIn['lanePolicy']
值。同样,如果dfIn['seed']
匹配两个给定的行,则dfIn['densitiy']
也将匹配。我想计算一个类似于以下内容的表:dfDesired = pd.DataFrame({'seed':[1324367672,1324367673,1324367674],
'stepsTrue':[40,93,23], 'stepsFalse':[37,72,70], 'stepsDiff':[3, 21, -47], 'density':[51,208,149]})
seed stepsTrue stepsFalse stepsDiff density
0 1324367672 40 37 3 51
1 1324367673 93 72 21 208
2 1324367674 23 70 -47 149
特别是,我正在寻找
dfDesired['stepsDiff']
中的值,这是关联的dfIn['stepsPerTrip']
的False
和每对匹配的True
对的dfIn['lanePolicy']
的dfIn['seed']
值之间的差异。还请注意,dfDesired
的行数应为dfIn
的一半。我能够使用以下方法计算该单列的值:
dfDiff = dfIn.loc[dfIn['lanePolicy'] == True]['stepsPerTrip'].reset_index()['stepsPerTrip'] - dfIn.loc[dfIn['lanePolicy'] == False]['stepsPerTrip'].reset_index()['stepsPerTrip']
0 3
1 21
2 -47
Name: stepsPerTrip, dtype: int64
但是,我想创建一个保留其他列的新DataFrame。我也尝试了以下方法,但是得到了不正确的结果:
dfDesired = dfIn.groupby('seed').apply(lambda x:x.loc[x['lanePolicy']==True]['stepsPerTrip']-x.loc[x['lanePolicy']==False]['stepsPerTrip'])
seed
1324367672 0 NaN
1 NaN
1324367673 2 NaN
3 NaN
1324367674 4 NaN
5 NaN
Name: stepsPerTrip, dtype: float64
先感谢您。
最佳答案
使用DataFrame.pivot
,用Series.sub
减去列,对于density
列,将带有seed
的系列添加为与DataFrame.drop_duplicates
不重复的系列:
df = dfIn.pivot('seed','lanePolicy','stepsPerTrip').add_prefix('steps')
df['stepsDiff'] = df['stepsTrue'].sub(df['stepsFalse'])
df['density'] = dfIn.drop_duplicates('seed').set_index('seed')['density']
df = df.reset_index().rename_axis(None, axis=1)
print (df)
seed stepsFalse stepsTrue stepsDiff density
0 1324367672 37 40 3 51
1 1324367673 72 93 21 208
2 1324367674 70 23 -47 149
另一个解决方案是使用
DataFrame.pivot_table
和默认聚合函数mean
(如果列seed
,'density'和lanePolicy
中有重复项):df = (dfIn.pivot_table(index=['seed','density'], columns='lanePolicy',values='stepsPerTrip')
.add_prefix('steps'))
df['stepsDiff'] = df['stepsTrue'].sub(df['stepsFalse'])
df = df.reset_index().rename_axis(None, axis=1)
print (df)
seed density stepsFalse stepsTrue stepsDiff
0 1324367672 51 37 40 3
1 1324367673 208 72 93 21
2 1324367674 149 70 23 -47