Given a DataFrame
with a multi-level index (in this example 'userId' & 'date' are part of the index):
clicks
userId date
x 1/1 1
1/2 2
y 1/1 3
1/3 4
z 1/1 4
And given a Series
that has values from the first level of the DataFrame's multi-index as its own index:
x Alice
z Charlie
y Bob
How can the first level of the DataFrame index be updated to be the values from a Series? The resulting DataFrame would look like
Alice 1/1 1
1/2 2
Bob 1/1 3
1/3 4
Charlie 1/1 4
Note: I cannot rely on the ordering of the Series being the same ordering as the first level of the multi-index (e.g. the Series index is ['x', 'z', 'y'] while the DataFrame first-level is ['x', 'y', 'z'])
Thank you in advance for your consideration and response.
Map the level using the Series, then assign the index back.
import pandas as pd
df.index = pd.MultiIndex.from_arrays(
[df.index.get_level_values('userId').map(s), # s is your Series
df.index.get_level_values('date')])
clicks
userId date
Alice 1/1 1
1/2 2
Bob 1/1 3
1/3 4
Charlie 1/1 4
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다