[英]adding two columns in multiindex dataframe pandas
我正在使用 pandas 1.14。
我有 dataframe 看起來像這樣:
col1 col2 ....
A B C D E
11 1 1 1 1 2 3
3 3 4
30 3 10 2
... ...
22 3 4 5 6 3 1
df.index
輸出
MultiIndex([('11', '1', '1', '1', '1'),
('11', '1', '1', '1', '3'),
('11', '1', '1', '30', '3'),
...
('22', '3', '4', '5', '6')],
names=["A","B","C", "D", "E"], length=10000)
df.columns
輸出
Index(["col1", "col2", ...], dtype="object")
我想做的是添加兩列並除以 2。在單個索引 dataframe 我通常會做df["new"] = (df["col1"] + df["col2"])/2
如何使用多索引 dataframe 做到這一點?
我想要的 dataframe 應該是這樣的
col1 col2 new
A B C D E
11 1 1 1 1 2 3 2.5
3 3 4 3.5
30 3 10 2 6
... ...
22 3 4 5 6 3 1 2
提前致謝!
您的解決方案也應該適用於 MultiIndexes
In [14]: df = pd.DataFrame([[2,3],[3,4],[10,2],[3,1]], columns=['col1', 'col2'], index=index)
In [15]: df
Out[15]:
col1 col2
A B C D E
11 1 1 1 1 2 3
3 3 4
30 3 10 2
22 3 4 5 6 3 1
In [16]: df['new'] = (df['col1'] + df['col2'])/2
In [17]: df
Out[17]:
col1 col2 new
A B C D E
11 1 1 1 1 2 3 2.5
3 3 4 3.5
30 3 10 2 6.0
22 3 4 5 6 3 1 2.0
我做了一個實驗,你的方法應該有效。
df = pd.DataFrame({'a':[1,2,3,4], 'b':[2,3,4,5]}, index=[['1', '1', '2', '2'], ['1','2','1','2']])
df
>>>
a b
1 1 1 2
2 2 3
2 1 3 4
2 4 5
你的方法。
df['new'] = (df['a'] + df['b']) / 2
df
>>>
a b new
1 1 1 2 1.5
2 2 3 2.5
2 1 3 4 3.5
2 4 5 4.5
```
無特殊處理,標准手法。 我的標准是始終使用assign()
df = pd.DataFrame({"A":[11],"B":[1],"C":[1],"D":[1],"E":[1],"col1":[2],"col2":[3]})
df = df.set_index(["A","B","C","D","E"])
df = df.assign(new=lambda dfa: dfa.sum(axis=1)/2)
print(df.to_string())
col1 col2 new
A B C D E
11 1 1 1 1 2 3 2.5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.