我是 Pandas 的初學者。我有兩個資料框 df1 和 df2,每個資料框有三列,由一些索引標記。
我想獲得第三個資料幀,其每列的條目為 min( df1-df2, 1-df1-df2 ),同時保留索引。
我不知道如何一次在所有三列上執行此操作。如果我嘗試例如np.min( df1-df2, 1-df1-df2 )
我得到TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
,而min( df1-df2, 1-df1 df2 )
給出ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我不能使用apply
,因為我有多個資料框。基本上,我想使用類似的東西subtract
,但能夠定義我自己的函式。
示例:考慮這兩個資料幀
df0 = pd.DataFrame( [[0.1,0.2,0.3], [0.3, 0.1, 0.2], [0.1, 0.3, 0.9]], index=[2,1,3], columns=['px', 'py', 'pz'] )
In [4]: df0
Out[4]:
px py pz
2 0.1 0.2 0.3
1 0.3 0.1 0.2
3 0.1 0.3 0.9
和
df1 = pd.DataFrame( [[0.9,0.1,0.9], [0.1,0.2,0.1], [0.3,0.1,0.8]], index=[3,1,2], columns=['px', 'py', 'pz'])
px py pz
3 0.9 0.1 0.9
1 0.1 0.2 0.1
2 0.3 0.1 0.8
我想要的輸出是一個新的資料框df,由三列'px'、'py'、'pz'組成,其條目是:
for j in range(1,4):
dfx[j-1] = min( df0['px'][j] - df1['px'][j], 1 - df0['px'][j] df1['px'][j] )
對于 df['px'],同樣對于 'py' 和 'pz'。
px py pz
1 0.2 -0.1 0.1
2 -0.2 0.1 -0.5
3 -0.8 0.2 0.0
我希望現在很清楚!提前致謝!
uj5u.com熱心網友回復:
pandas
足夠聰明,可以以矢量化的方式為您匹配列和索引值。如果您正在回圈資料框,那么您可能做錯了。
m1 = df0 - df1
m2 = 1 - (df0 df1)
# Take the values from m1 where they're less than
# The corresponding value in m2. Otherwise, take m2:
out = m1[m1.lt(m2)].combine_first(m2)
# Another method: Combine our two calculated frames,
# groupby the index, and take the minimum.
out = pd.concat([m1, m2]).groupby(level=0).min()
print(out)
# Output:
px py pz
1 0.2 -0.1 0.1
2 -0.2 0.1 -0.5
3 -0.8 0.2 -0.8
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506829.html
下一篇:IF-資料幀R中樞軸更長的函式