簡體   English   中英

有沒有辦法向僅與一個級別對齊的 pandas 多索引添加新列?

[英]Is there a way to add a new column to a pandas multiindex that only aligns with one level?

我正在尋找一種將列添加到多索引 dataframe 的干凈方法,其中每個級別 = 0 僅重復一次該值。

例如,

我想為此添加一列:

索引級別=0 索引級別=1 值 (x)
一個 1 300
2 850
3 2000
1 100
2 70
3 400

為了達到這個目的:

索引級別=0 索引級別=1 值 (x) 值 (y)
一個 1 300 黃色
2 850
3 2000
1 100 紅色的
2 70
3 400

想要這個:

索引級別=0 索引級別=1 值 (x) 值 (y)
一個 1 300 黃色
2 850 黃色
3 2000 黃色
1 100 紅色的
2 70 紅色的
3 400 紅色的

我不確定如何最好地在這里創建一個表來顯示我希望的內容,但對我來說重要的部分是 y 對應於索引級別 = 0 的所有行,但對於索引級別的每個增量都不會重復=1。 我確信我可以使用 null 值在 y 列中添加額外的行,但我認為可能有更優雅的方式。

使用pd.IndexSlice

idx = pd.IndexSlice
df.loc[idx[:, 1], 'Color'] = ['Yellow', 'Red']
print(df)

# Output
     Value   Color
A 1    300  Yellow
  2    850     NaN
  3   2000     NaN
B 1    100     Red
  2     70     NaN
  3    400     NaN

或僅使用slice

df.loc[(slice(None), 1), 'Color'] = ['Yellow', 'Red']
print(df)

# Output
     Value   Color
A 1    300  Yellow
  2    850     NaN
  3   2000     NaN
B 1    100     Red
  2     70     NaN
  3    400     NaN

您尚未指定如何確定高/低,因此我將它們硬編碼在字典中:

# Create the data frame
index = pd.MultiIndex.from_product([['A', 'B'], [1,2,3]])
df = pd.DataFrame({
    'x': [300, 850, 2000, 100, 70, 400]
}, index=index)

# The transformation
def f(col):
    y_values = {
        'A': 'High',
        'B': 'Low'
    }
    level0 = col.index[0][0]
    return [y_values[level0]] + [''] * (len(col) - 1)

df['y'] = df.groupby(level=0).transform(f)

遍歷 index0 並為 index0 中每種新數據類型的新列賦值:

c=0
for i in df.index:
    if i[0] != c:
        #put your code here to add values to new column
        c = i[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM