我有以下Pd系列
count area volume formula quantity
0 1.0 22 NaN count 1.0
1 1.0 15 NaN count 1.0
2 1.0 1.4 NaN area 1.4
3 1.0 0.6 10 volume 100
數量列基于通過查找公式列中的值,例如行(0)是“計數”所以它是 1,行(2)是“面積”所以它是 1.4
為此,我有以下公式
Merged['quantity']=Merged.apply(lambda x: x[x['QuantityFormula']] , axis=1)
然而,體積的數量是一個計算欄位:體積 * 10。我寫了一個函式來計算兩者
def func(x):
if x[x['QuantityFormula']] == Volume:
return volume * 10
else:
return x[x['QuantityFormula']]
df['Classification'] = Merged['QuantityFormula'].apply(func)
但是我收到以下錯誤
Error: string indices must be integers
有任何想法嗎?謝謝
回答
def func(row):
if row['QuantityFormula'] == 'Volume':
return row['Volume'] * 10
return row[row['quantity']]
Merged['Ans'] = Merged.apply(func, axis=1)
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
df.apply(lambda x: x['volume']*10 if x['formula'] == 'volume' else x['quantity'], axis=1)
print(df)
count area volume formula quantity ans
0 1.0 22.0 NaN count 1.0 1.0
1 1.0 15.0 NaN count 1.0 1.0
2 1.0 1.4 NaN area 1.4 1.4
3 1.0 0.6 10.0 volume 100.0 100.0
使用顯式函式,您可以執行以下操作:
def func(row):
if row['formula'] == 'volume':
return row['volume'] * 10
return row['quantity']
df.apply(func, axis=1)
uj5u.com熱心網友回復:
使用查找:
import numpy as np
s = df['formula'].str.lower()
m = s.eq('volume')
idx, cols = pd.factorize(s)
df['quantity'] = (df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx]
* np.where(m, 10, 1)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/533416.html
標籤:Python熊猫
上一篇:熊貓:將列添加到另一列
