![](/img/trans.png)
[英]Fill in a pandas DataFrame bucketing the values of a column of a different frame and preserving the index
[英]Pandas data frame fill null values with index
我有一個數據框,我想用一個列填充索引值的空值。 這樣做的最佳方式是什么?
說我的數據框看起來像這樣:
>>> import numpy as np
>>> import pandas as pd
>>> d=pd.DataFrame(index=['A','B','C'], columns=['Num','Name'], data=[[1,'Andrew'], [2, np.nan], [3, 'Chris']])
>>> print d
Num Name
A 1 Andrew
B 2 NaN
C 3 Chris
我可以使用以下代碼行來獲取我正在尋找的內容:
d['Name'][d['Name'].isnull()]=d.index
但是,我收到以下警告:“正在嘗試在DataFrame的切片副本上設置值”
我認為使用fillna或loc這樣做會更好,但我無法弄清楚如何使用fillna或loc。 我嘗試過以下方法:
>>> d['Name']=d['Name'].fillna(d.index)
>>> d.loc[d['Name'].isnull()]=d.index
有哪些建議是最好的選擇?
我會在這種情況下使用.loc
,如下所示:
d.loc[d['Name'].isnull(), 'Name'] = d.loc[d['Name'].isnull()].index
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.