Use reset_index()
to convert the Series to a DataFrame and the index to a column, and then apply
your function to the DataFrame.
The tricky part is knowing how reset_index()
names the columns, so here are a couple of examples.
With a Singly Indexed Series
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
Output:
idx1 I made this with index idx1 and value val1
idx2 I made this with index idx2 and value val2
dtype: object
With a Multi-Indexed Series
Same concept here, but you'll need to access the index values as row['level_*']
because that's where they're placed by 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
Output:
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
If your series or indexes have names, you will need to adjust accordingly.