![](/img/trans.png)
[英]Add a new column to a dataframe from a Series or dictionary mapping my series index and a dataframe column to key pandas python
[英]How to create a dictionary of series with an index from a dataframe in python
我有以下 dataframe
df = pd.DataFrame({'col_1': ['Animal','Deer','Sheep','Fish','Vehicle','Truck','Car','Mineral','Gold','Silver'],
'col_2': ['Animal',0.5,0.25,0.25,'Vehicle',0.5,0.5,'Mineral',0.75,0.25],
'Group': [0,0,0,0,1,1,1,2,2,2]})
我想創建一個系列字典。 我希望第 1 列是索引,第 2 列是值,組來指定系列。 EG 第一個系列的名稱(鍵)將是“Animal”,它應該看起來像:
我試過以下。 但這不對,我得到的是數據框字典而不是系列,並且標題位於第一行。
dict_of_series = {i: df.loc[df.group == i, ['col_1', 'col_2']] for i in range(1, df.group.iat[-1])}
利用:
dict_of_series = {g['col_2'].iat[0]:
g.set_axis(g.iloc[0], axis=1).iloc[1:, :-1].rename_axis(None, axis=1)
for i, g in df.groupby('Group')}
print (dict_of_series['Animal'])
Animal Animal
1 Deer 0.5
2 Sheep 0.25
3 Fish 0.25
print (dict_of_series['Vehicle'])
Vehicle Vehicle
5 Truck 0.5
6 Car 0.5
print (dict_of_series['Mineral'])
Mineral Mineral
8 Gold 0.75
9 Silver 0.25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.