【问题标题】:(Python) How to only keep specific part of cells in a dataframe(Python)如何只将特定部分的单元格保留在数据框中
【发布时间】:2021-12-10 15:31:16
【问题描述】:

我想清理我的数据框的源列。最后我只想保留'name'后面的部分。

最好的方法是什么? 例如:

第 1 行,第 1 列: {'id': 'rtl-nieuws', 'name': 'RTL Nieuws'}

第 2 行,第 1 列: {'id': 'none', 'name': 'www.ad.nl'}

期望的结果:

第 1 行,第 1 列: RTL 新闻

第 2 行,第 1 列: www.ad.nl

【问题讨论】:

  • 数据框是否包含字典或字符串?

标签: python pandas dataframe


【解决方案1】:

这是你想要做的吗?将来,请考虑给出一个工作示例来解决来自的请求。

data = pd.DataFrame({
    "id": ["rtl-nieuws", "none"],
    "name": ["RTL Nieuws", "www.ad.nl"]
}, index=[0,1])


data.drop("id", axis = 1)

#     name
# 0   RTL Nieuws
# 1   www.ad.nl

【讨论】:

    【解决方案2】:

    考虑到您的数据似乎是字典的格式,您可以使用 ast.literal_eval() 来访问 'name' 键处的值。

    import ast
    
    current_cell = "{'id': 'rtl-nieuws', 'name': 'RTL Nieuws'}"
    name = ast.literal_eval(current_cell)['name']
    print(name)
    

    >>> RTL 新闻

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      相关资源
      最近更新 更多