簡體   English   中英

如何根據行中的另一個值在 dataframe 中創建列(Python)

[英]How to create a column in a dataframe based on another value in the row (Python)

我有以下數據:

國家 代碼 大陸 植物 無脊椎動物 脊椎動物 全部的
阿富汗 AFG 亞洲 5 2 33 40
阿爾巴尼亞 ALB 歐洲 5 71 61 137
阿爾及利亞 DZA 非洲 24 40 81 145

我想添加一個由引用列表的大陸確定的半球列。 我想使用自定義 function (而不是使用 lambda)來做到這一點。

我嘗試了以下操作:

northern = ['North America', 'Asia', 'Europe']
southern = ['Africa','South America', 'Oceania']

def hem(x,y):
    if y in northern:
        x = 'northern'
        return x
       
    elif y in southern:
        x = 'southern'
        return x
           
    else:
        x = 'Not Found'
        return x

species_custom['hemisphere'] = species_custom.apply(hem, args=(species_custom['continent'],), axis=1)

我收到以下錯誤:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')

有什么想法我哪里出錯了嗎?

hem被定義為服用兩個 arguments 但在apply中你只通過一個。 當你這樣做時,你正在將整個continent列傳遞給它。 可能不是你想要的。

您可以通過使用嵌套numpy來簡化where .

import numpy as np

df['hemisphere'] = np.where(df['continent'].isin(northern), 'northern', np.where(df['continent'].isin(southern),'southern','Not Found'))

結果

       country code continent  plants  invertebrates  vertebrates  total  hemisphere
0  Afghanistan  AFG      Asia       5              2           33     40    northern 
1      Albania  ALB    Europe       5             71           61    137    northern 
2      Algeria  DZA    Africa      24             40           81    145    southern 

暫無
暫無

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

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