sap*_*ico 2 python indexing series multi-index pandas
我正在尝试将一个系列设置为另一个具有多个索引的值。如果没有复杂的技巧,我无法在Pandas中找到一种方法。
我的原始系列:
one 1 0.522764
3 0.362663
7 0.963108
two 2 0.717855
4 0.004645
5 0.077471
Run Code Online (Sandbox Code Playgroud)
我要连接的数据,级别为three
:
2 0.8
7 0.9
8 0.7
Run Code Online (Sandbox Code Playgroud)
所需的输出:
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
Run Code Online (Sandbox Code Playgroud)
我无法找出在熊猫中做到这一点的优雅方法。我所能做的就是以下黑客:
# 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})
Run Code Online (Sandbox Code Playgroud)
这是我目前正在解决的方式:
# 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)
Run Code Online (Sandbox Code Playgroud)
这将产生所需的输出。
问题:在Pandas中,有没有简单,优雅的方法可以做到这一点?
您可以尝试使用pd.concat
:
u = (new_data.to_frame()
.assign(_='three')
.set_index(['_', new_data.index])[0])
pd.concat([df, u])
one 1 0.618472
3 0.026207
7 0.766849
two 2 0.651633
4 0.282038
5 0.160714
three 1 0.900000
2 0.700000
3 0.800000
dtype: float64
Run Code Online (Sandbox Code Playgroud)
选项1
pd.concat
是一种通过使用keys
参数预先添加索引或列级别的便捷方法。将此与一秒钟相结合pd.concat
以完成工作。
pd.concat([my_series, pd.concat([new_data], keys=['Three'])])
one 1 0.943246
3 0.412200
7 0.379641
two 2 0.883960
4 0.182983
5 0.773227
Three 1 0.900000
2 0.700000
3 0.800000
dtype: float64
Run Code Online (Sandbox Code Playgroud)
选项 2
或者我们可以在向index
参数中插入一个附加数组的同时构造一个新系列。pd.concat
再次使用组合。 注意 我本可以使用,pd.MultiIndex.from_arrays
但通过将数组直接传递给index
参数来简化语法。
pd.concat([
my_series,
pd.Series(new_data.values, [['Three'] * new_data.size, new_data.index])
])
one 1 0.943246
3 0.412200
7 0.379641
two 2 0.883960
4 0.182983
5 0.773227
Three 1 0.900000
2 0.700000
3 0.800000
dtype: float64
Run Code Online (Sandbox Code Playgroud)
选项 3
使用多索引重建序列的另一种方法。这个使用pd.MultiIndex.from_product
.
pd.concat([
my_series,
pd.Series(new_data.values, pd.MultiIndex.from_product([['Three'], new_data.index]))
])
one 1 0.943246
3 0.412200
7 0.379641
two 2 0.883960
4 0.182983
5 0.773227
Three 1 0.900000
2 0.700000
3 0.800000
dtype: float64
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
468 次 |
最近记录: |