【问题标题】:dataframe.set_index; TypeError: '<' not supported between instances of 'str' and 'int'数据框.set_index;类型错误:“str”和“int”的实例之间不支持“<”
【发布时间】:2026-01-11 18:25:01
【问题描述】:

我正在尝试将 Pandas.Dataframe 列表转换为字典列表,并尝试使用“id”列作为我的 dic 的键。并非我所有的数据框都有id 列,所以我之前检查过,有些 id 列没有。但是,我的结果都没有使用 id 列作为键:

for dataframe in dataframes:
        if 'id' in dataframe.columns:
            cleaned_dic =  dataframe.set_index('id').T.to_dict('dict')
            else: 
            cleaned_dic = dataframe.T.to_dict('dict')

json 中的示例结果

{
  "0": {
    "date": "2020-01-03",
    "id": 9,
    "journal": "Journal of photochemistry and photobiology. B, Biology",
    "title": "Gold nanoparticles synthesized from Euphorbia fischeriana root by green route method alleviates the isoprenaline hydrochloride induced myocardial infarction in rats."
  },
  "1": {
    "date": "01/01/2020",
    "id": 10,
    "journal": "The journal of maternal-fetal & neonatal medicine",
    "title": "Clinical implications of umbilical artery Doppler changes after betamethasone administration"
  },
  "2": {
    "date": "01/01/2020",
    "id": "11",
    "journal": "Journal of back and musculoskeletal rehabilitation",
    "title": "Effects of Topical Application of Betamethasone on Imiquimod-induced Psoriasis-like Skin Inflammation in Mice."
  },
  "3": {
    "date": "01/03/2020",
    "id": "12",
    "journal": "Journal of back and musculoskeletal rehabilitation",
    "title": "Comparison of pressure release, phonophoresis and dry needling in treatment of latent myofascial trigger point of upper trapezius muscle."
  }
}

【问题讨论】:

  • 您的代码和数据与问题的标题无关。请添加您遇到的错误的代码和堆栈跟踪或更正标题。

标签: python pandas


【解决方案1】:

我认为 .set_index('id') 方法失败了,因为它试图对“id”列进行排序,但它找到了 INT 和 STR。

在使用 .set_index('id') 之前,您应该转换“id”列,以使该系列中的所有值都具有相同的类型、INT 或 STR。

在设置索引之前,您可以尝试对数据框执行类似操作:

# raising errors
df.astype({'id': 'int64'}, errors='raise')
# ignoring errors
df.astype({'id': 'int64'}, errors='ignore')

【讨论】:

    【解决方案2】:

    尝试使用此代码:

    d = {}
    for dataframe in dataframes:
        d[dataframe['id']] = dataframe.to_dict()
    

    【讨论】:

      最近更新 更多