英文:
How can I add a new column filled with values to a pandas DataFrame without getting NaN values?
问题
我是 Python 新手,正在尝试添加一个新的列,并填充值,但运行代码时显示 NaN。
[![在这里输入图片描述](https://i.stack.imgur.com/Xoyw8.jpg)](https://i.stack.imgur.com/Xoyw8.jpg)
df0 = pd.DataFrame({'GOV': ['Iraq', 'Pakistan', 'UAE', 'UK'], 'CAPITAL': ['Baghdad', 'Islamabad', 'DUBAI', 'LONDON'], 'POPULATION': [100, 300, 120, 150]}, columns=['GOV', 'CAPITAL', 'POPULATION'])
df0.index = ['A', 'B', 'C', 'D']
lang = pd.Series(['Arabic', 'Urdu', 'Arabic', 'English'], index=['Iraq', 'Pakistan', 'UAE', 'UK'], name='language')
df0['language'] = lang
<details>
<summary>英文:</summary>
I new to Python , I am trying to add new column filled with values but when run the code it shows NaN .
[![enter image description here](https://i.stack.imgur.com/Xoyw8.jpg)](https://i.stack.imgur.com/Xoyw8.jpg)
df0 = pd.DataFrame ({ 'GOV': [ 'Iraq' , 'Pakistan' , 'UAE' , 'UK' ] , 'CAPITAL' : [ 'Baghdad' , 'Islamabad' , 'DUBAI' , 'LONDON' ], 'POPULATION' : [100 , 300 , 120 , 150]
}, columns = ['GOV' , 'CAPITAL' , 'POPULATION'])
df0.index = ['A' , 'B' , 'C' , 'D']
lang = pd.Series(['Arabic', 'Urdu' , 'Arabic' , 'English'] ,index = ['Iraq' , 'Pakistan' , 'UAE' , 'UK'] , name = 'language'
)
df0['language'] = lang
</details>
# 答案1
**得分**: 3
您已经设置了`lang`的索引,但与`df0`的索引不匹配。
改为使用`pd.merge`:
```python
df0 = pd.merge(df0, lang, left_on="GOV", right_index=True)
英文:
You have set the index of lang
which does not match with the index of df0
.
Instead, use pd.merge
:
df0 = pd.merge(df0, lang, left_on="GOV", right_index=True)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论