我試圖將一個系列設置爲另一個系列,處於多索引值。沒有複雜的黑客攻擊,我無法在熊貓中找到辦法。在一個熊貓MultiIndex系列中設置值
我原來的系列:
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
我想不出一個優雅在熊貓中這樣做的方法。所有我已經能夠做的就是下面的技巧:
# 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)
這將產生所需的輸出。
問:是否有一個簡單,優雅的方式來做到這一點在熊貓?
你的符號是有點混亂,因爲'df'不是數據框... – C8H10N4O2
相關:https://stackoverflow.com/questions/18062135/combining-two-series-into-a-dataframe-熊貓? – C8H10N4O2
@ C8H10N4O2被抓住了,修好了 –