gpt4 book ai didi

python - Pandas : add column to multiindex dataframe at the end

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:03 26 4
gpt4 key购买 nike

有人可以帮我向多索引数据框添加一列吗?

我有以下多索引数据框:

                    price     
sym i_date
MSFT 2017-04-04 100.78
2017-04-05 100.03
2017-04-06 100.76
2017-04-07 100.76

AAPL 2017-04-04 144.77
2017-04-05 144.02
2017-04-06 143.66
2017-04-07 143.66

我想在价格列之后添加一列,它是价格的自然对数:

                    price      ln price
sym i_date
MSFT 2017-04-04 100.78 <ln (100.78)>
2017-04-05 100.03 <ln (100.03)>
2017-04-06 100.76 <ln (100.76)>
2017-04-07 100.76 <ln (100.76)>

AAPL 2017-04-04 144.77 <ln (144.77)>
2017-04-05 144.02 <ln (144.02)>
2017-04-06 143.66 <ln (143.66)>
2017-04-07 143.66 <ln (143.66)>

我尝试了以下但它没有改变数据帧。

for stk_sym in df.index.get_level_values('stk_sym').unique():
df.loc[stk_sym]['ln price'] = np.log(df.ix[stk_sym]['price'])

最佳答案

您可以将值设置为:

代码:

df['ln price'] = np.log(df['price'])

测试代码:

df = pd.read_fwf(StringIO(u"""
sym i_date price
MSFT 2017-04-04 100.78
MSFT 2017-04-05 100.03
MSFT 2017-04-06 100.76
MSFT 2017-04-07 100.76
AAPL 2017-04-04 144.77
AAPL 2017-04-05 144.02
AAPL 2017-04-06 143.66
AAPL 2017-04-07 143.66"""),
header=1).set_index(['sym', 'i_date'])

df['ln price'] = np.log(df['price'])

print(df)

结果:

                  price  ln price
sym i_date
MSFT 2017-04-04 100.78 4.612940
2017-04-05 100.03 4.605470
2017-04-06 100.76 4.612741
2017-04-07 100.76 4.612741
AAPL 2017-04-04 144.77 4.975146
2017-04-05 144.02 4.969952
2017-04-06 143.66 4.967449
2017-04-07 143.66 4.967449

关于python - Pandas : add column to multiindex dataframe at the end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43433300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com