[英]Is there no syntax suger for dynamic creating columns with multiindexed pandas dataframe?
[英]Creating multiple new columns in a multiindexed pandas dataframe
當數據幀是多索引時,是否可以在Pandas中創建多個新列? 我想補充一兩個新列one
和two
下bar2
supercolumn。 像這樣......
import pandas as pd
import numpy as np
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'],
['one', 'two', 'one', 'two', 'one', 'two']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 6), index=[1, 2, 3], columns=index)
df["bar2", ["one", "two"]] = np.random.randn(3, 2)
我知道我可以逐個創建它們
df["bar2", "one"] = np.random.randn(3,1)
df["bar2", "two"] = np.random.randn(3,1)
有沒有更快的方法同時做兩件事?
In [270]:
df_to_add = pd.DataFrame(np.random.randn(3,2) , columns=[['bar2' , 'bar2'] , ['one' , 'two']] , index = [1 , 2 , 3])
df_to_add
Out[270]:
bar2
one two
1 0.119730 -0.265579
2 1.777329 -1.178128
3 -2.700409 0.457430
In [271]:
pd.concat([df , df_to_add] , axis = 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.