我有一个DataFrame:
>>> df
STK_ID EPS cash
STK_ID RPT_Date
601166 20111231 601166 NaN NaN
600036 20111231 600036 NaN 12
600016 20111231 600016 4.3 NaN
601009 20111231 601009 NaN NaN
601939 20111231 601939 2.5 NaN
000001 20111231 000001 NaN NaN
Run Code Online (Sandbox Code Playgroud)
然后我只想要那些EPS不是NaN,df.drop(....)即将返回数据帧的记录,如下所示:
STK_ID EPS cash
STK_ID RPT_Date
600016 20111231 600016 4.3 NaN
601939 20111231 601939 2.5 NaN
Run Code Online (Sandbox Code Playgroud)
我怎么做?
我有一个dataFrame有几个coulmns,所以我选择了一些coulmns来创建一个这样的变量xtrain = df[['Age','Fare', 'Group_Size','deck', 'Pclass', 'Title' ]]我想从这些coulmns中删除所有原始数据,主数据框架中的Survive coulmn是nan.
我知道有很多关于这个警告的帖子,但我无法找到解决方案.这是我的代码:
df.loc[:, 'my_col'] = df.loc[:, 'my_col'].astype(int)
#df.loc[:, 'my_col'] = df.loc[:, 'my_col'].astype(int).copy()
#df.loc[:, 'my_col'] = df['my_col'].astype(int)
Run Code Online (Sandbox Code Playgroud)
它产生警告:
SettingWithCopyWarning:尝试在DataFrame的切片副本上设置值.尝试使用.loc [row_indexer,col_indexer] = value
即使我按照建议更改了代码,我仍然会收到此警告?我需要做的就是转换一列的数据类型.
**备注:**最初该列的类型为float,具有一位小数(例如:4711.0).因此我将其更改为整数(4711)然后更改为字符串('4711') - 只是为了删除小数.
感谢您的帮助!
更新:该警告对过滤之前完成的原始数据的过滤产生了副作用.我错过了DataFrame.copy().使用副本代替,解决了问题!
df = df[df['my_col'].notnull()].copy()
df.loc[:, 'my_col'] = df['my_col'].astype(int).astype(str)
#df['my_col'] = df['my_col'].astype(int).astype(str) # works too!
Run Code Online (Sandbox Code Playgroud)