用于reset_index()
将 Series 转换为 DataFrame 并将索引转换为列,然后apply
将您的函数转换为 DataFrame。
棘手的部分是知道如何reset_index()
命名列,所以这里有几个例子。
具有单索引系列
s=pd.Series({'idx1': 'val1', 'idx2': 'val2'})
def use_index_and_value(row):
return 'I made this with index {} and value {}'.format(row['index'], row[0])
s2 = s.reset_index().apply(use_index_and_value, axis=1)
# The new Series has an auto-index;
# You'll want to replace that with the index from the original Series
s2.index = s.index
s2
输出:
idx1 I made this with index idx1 and value val1
idx2 I made this with index idx2 and value val2
dtype: object
使用多索引系列
这里的概念相同,但您需要访问索引值,row['level_*']
因为它们是由Series.reset_index()
.
s=pd.Series({
('idx(0,0)', 'idx(0,1)'): 'val1',
('idx(1,0)', 'idx(1,1)'): 'val2'
})
def use_index_and_value(row):
return 'made with index: {},{} & value: {}'.format(
row['level_0'],
row['level_1'],
row[0]
)
s2 = s.reset_index().apply(use_index_and_value, axis=1)
# Replace auto index with the index from the original Series
s2.index = s.index
s2
输出:
idx(0,0) idx(0,1) made with index: idx(0,0),idx(0,1) & value: val1
idx(1,0) idx(1,1) made with index: idx(1,0),idx(1,1) & value: val2
dtype: object
如果您的系列或索引有名称,则需要进行相应调整。