【发布时间】:2018-02-02 07:15:17
【问题描述】:
我正在尝试以多索引值将一个系列设置为另一个系列。如果没有复杂的 hack,我无法在 Pandas 中找到一种方法。
我的原创系列:
one 1 0.522764
3 0.362663
7 0.963108
two 2 0.717855
4 0.004645
5 0.077471
我要连接的数据,级别为three:
2 0.8
7 0.9
8 0.7
想要的输出:
one 1 0.522764
3 0.362663
7 0.963108
two 2 0.717855
4 0.004645
5 0.077471
three 2 0.800000
7 0.900000
8 0.700000
我无法在 pandas 中找到一种优雅的方式来做到这一点。我所能做的就是以下黑客攻击:
# imports
import numpy as np
import pandas as pd
# to replicate the Series:
np.arrays = [['one','one','one','two','two','two'],[1,3,7,2,4,5]]
my_series = pd.Series([np.random.random() for i in range(6)],
index=pd.MultiIndex.from_tuples(list(zip(*np.arrays))))
# the new data I need to add:
new_data = pd.Series({1: .9, 2: .7, 3: .8})
这是我目前的解决方法:
# rename the index so that I can call it later
new_data.index.name = 'level_1'
# turn it into temporary a dataframe so that I can add a new column
temp = pd.DataFrame(new_data)
# create a new column with the desired name for first index level
temp['level_0'] = 'three'
# reset index, set the new index, turn into Series again
temp = temp.reset_index().set_index(['level_0', 'level_1'])[0]
# append it to the larger dataframe
my_series = my_series.append(temp)
这会产生所需的输出。
问题:在 Pandas 中是否有一种简单、优雅的方式来做到这一点?
【问题讨论】:
-
您的符号有点混乱,因为
df不是 DataFrame... -
@C8H10N4O2 抓得好,修好了
-
我们的回答有帮助吗?
标签: python pandas indexing series multi-index