我有一個 4 列的 DataFrame。我想計算三列的日志形式,然后制作一個新的DataFrame。
year gnp labor capital
0 1955 114043 8310 182113
1 1956 120410 8529 193745
2 1957 129187 8738 205192
3 1958 134705 8952 215130
這就是我的 DataFrame 的樣子。我想計算除“年份”之外的所有列的日志值。這是我的代碼:
ln_gnp = np.log(df.gnp)
ln_labor = np.log(df.labor)
ln_capital = np.log(df.capital)
現在,我想用“year”、“ln_gnp”、“ln_labor”和“ln_capital”創建一個新的 DataFrame。我嘗試了一些方法,但都沒有給我想要的結果。
uj5u.com熱心網友回復:
考慮以下簡單資料集:
df = pd.DataFrame({'year':[1,2,3,4,5],
'gnp':[100, 200, 300, 400, 500],
'labor':[1000, 2000, 3000, 4000, 5000],
'capital':[1e4, 2e4, 3e4, 4e4, 5e4]},
)
df

這是解決方案之一:
df['ln_gnp'] = np.log(df['gnp'])
df['ln_labor'] = np.log(df['labor'])
df['ln_capital'] = np.log(df['capital'])
df1=df[['year', 'ln_gnp', 'ln_labor', 'ln_capital']].copy()
df1
輸出:

uj5u.com熱心網友回復:
這是一種方法
更簡單的方法
# using applymap, take log for the three columns
# concat with the year column
df2=pd.concat([df['year'],
df[['gnp', 'labor','capital']].applymap(np.log)],
axis=1)
df2
year gnp labor capital
0 1955 11.644331 9.025215 12.112383
1 1956 11.698658 9.051227 12.174298
2 1957 11.769016 9.075437 12.231701
3 1958 11.810842 9.099632 12.278998
如果您需要使用您創建的系列,那么
# create a dataframe from the series you already created
df2=pd.DataFrame({'year': df['year'], 'gnp': ln_gnp, 'labor': ln_labor, 'capital' :ln_capital} )
df2
uj5u.com熱心網友回復:
另一種可能的解決方案:
df['ln_' df.columns[1:]] = np.log(df.iloc[:,1:])
輸出:
year gnp labor capital ln_gnp ln_labor ln_capital
0 1955 114043 8310 182113 11.644331 9.025215 12.112383
1 1956 120410 8529 193745 11.698658 9.051227 12.174298
2 1957 129187 8738 205192 11.769016 9.075437 12.231701
3 1958 134705 8952 215130 11.810842 9.099632 12.278998
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519505.html
上一篇:如何同時為缺失值和另一個資料框的資料集創建一個變數?
下一篇:從損壞的時間戳列中提取年份
