如何向 pandas DataFrame 添加一个新列并填充数值,而不会得到 NaN 值?

huangapple go评论64阅读模式
英文:

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=&quot;GOV&quot;, right_index=True)

huangapple
  • 本文由 发表于 2023年5月28日 22:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定