为什么我在尝试引用熊猫 df 列中的特定单元格时会"AttributeError: 'str' object has no attribute 'iloc"?



我知道有几种方法可以访问数据帧中特定单元格中的值,包括"iloc"。但是,当我尝试使用 iloc 时,我不断收到相同的错误 - 我也尝试将其切换为"loc",但得到不同的错误(特定于 indexError)。截取的代码如下: List_of_dfs 是 dfs 的列表,其中每个 df 都有相同的列。"性别"就是这样一列,带有"M"或"F"条目。

New_list_of_lists = 
[[(List_of_dfs[i]['HMW_Dosage_ISR']).max(),
(List_of_dfs[i]['Dose per Administration']).sum(),
List_of_dfs[i]['Sex'].iloc[0],
List_of_dfs[i]['ISR_Flag'].any()] for i in range(0,len(subject_IDs))]

这是我得到的:

List_of_dfs[i]['ISR_Flag'].any()] for i in range(0,len(subject_IDs))]
AttributeError: 'str' object has no attribute 'iloc'

我尝试用"性别"列注释掉该行,它工作正常,所以问题出在这个特定的列上。更多背景 - 当我做"List_of_dfs1[''].dtype时,我得到"dtype('O')"。

有什么想法吗?我基本上只是希望能够提取特定的性别并将其存储在New_list_of_lists中的相应位置。任何帮助将不胜感激。谢谢:)

编辑以包含示例数据:

List_of_dfs看起来像这样: List_of_dfs

Each df in List_of_dfs has several columns, with the following being of interest:
1) HMW_Dosage_ISR: dtype = float64
2) Dose per Administration: dtype = float64
3) Sex: dtype = 'O' - this value can either be 'M' or 'F'
4) ISR_Flag: dtype = bool

如果您运行List_of_dfs[i]['Sex'],那么您会注意到您恢复了str类型的pd.series。由于.iloc是一种pd.DataFrame的方法,在字符串对象上调用iloc会产生该错误。底线,您希望在数据帧上调用iloc,而不是系列上

要使代码正常工作,请执行以下操作

List_of_dfs[i].iloc[0, column_number_of_sex]

如果您有数据帧List_of_dfs[i],则用于访问['Sex']列的第一个值的语法为List_of_dfs[i].at[0, 'Sex']List_of_dfs[i].loc[:, 'Sex'].at[0]

相关内容

最新更新