[英]create iteratively multi index and multi columns dataframe in pandas
假設我要創建一個多索引和多列 dataframe:
X Y
Planet Continent Country A B C D
Earth Europe England 0.3 0.5 0.6 0.8
Europe Italy 0.1 0.2 0.4 1.2
Mars Tempe Sirtys 3.2 4.5 2.3 4.2
我想通過迭代收集 dataframe 的每一行來做到這一點,
row1 = np.array(['Earth', 'Europe', 'England', 0.3, 0.5, 0.6, 0.8])
row2 = np.array(['Earth', 'Europe', 'Italy', 0.1, 0.2, 0.4, 1.2])
我知道如何從行開始創建多列 dataframe,並且我知道如何創建多索引列。 但是我怎樣才能同時創建呢? 謝謝
如果您從一個空的 dataframe 開始定義多索引索引和列(據您所知):
df = pd.DataFrame(index=pd.MultiIndex(levels=[[]]*3,
codes=[[]]*3,
names=['Planet','Continent','Country']),
columns=pd.MultiIndex.from_tuples([('X','A'), ('X','B'),
('Y','C'), ('Y', 'D')],))
然后你可以像這樣添加每一行:
df.loc[tuple(row1[:3]), :]= row1[3:]
print (df)
X Y
A B C D
Planet Continent Country
Earth Europe England 0.3 0.5 0.6 0.8
之后又一次:
df.loc[tuple(row2[:3]), :]= row2[3:]
print (df)
X Y
A B C D
Planet Continent Country
Earth Europe England 0.3 0.5 0.6 0.8
Italy 0.1 0.2 0.4 1.2
但是如果您一次有很多行可用, @Yo_Chris的答案會更容易
row1 = np.array(['Earth', 'Europe', 'England', 0.3, 0.5, 0.6, 0.8])
row2 = np.array(['Earth', 'Europe', 'Italy', 0.1, 0.2, 0.4, 1.2])
# create a data frame and set index
df = pd.DataFrame([row1, row2]).set_index([0,1,2])
# set the index names
df.index.names = ['Planet', 'Continent', 'Country']
# create a multi-index and assign to columns
df.columns = pd.MultiIndex.from_tuples([('X', 'A'), ('X', 'B'), ('Y', 'C'), ('Y', 'D')])
X Y
A B C D
Planet Continent Country
Earth Europe England 0.3 0.5 0.6 0.8
Italy 0.1 0.2 0.4 1.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.