You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从DataFrame的Clue列按索引提取字符串格式的数据?

问题描述

现有如下表格数据:

WordClue
PATAction done while saying "Good dog"
RASCALSMischief-makers
PENIt might click for a writer

需要按索引提取Clue列的纯字符串数据,用于嵌入其他字符串场景。当前使用iloc方法返回的是DataFrame对象,导致嵌入后输出不符合预期:

执行代码:

x = df.iloc[[0],[1]]
y = "The answer for: {} Crossword Clue.".format(x)

得到的输出:

The answer for: Clue\n0 Action done while saying "Good dog" Crossword Clue.

期望输出:

The answer for: Action done while saying "Good dog" Crossword Clue.

解决方法

方法1:直接提取标量值

使用iloc时不要加方括号(方括号会返回DataFrame/Series),直接指定行和列的索引值,就能拿到纯字符串:

x = df.iloc[0, 1]  # 行索引0,列索引1
y = "The answer for: {} Crossword Clue.".format(x)

此时x就是目标字符串,嵌入后输出符合预期。

方法2:从已有DataFrame中提取字符串

如果已经得到了df.iloc[[0],[1]]这样的DataFrame对象,可以通过以下方式提取内部的字符串:

# 方法一:二次定位
x = df.iloc[[0],[1]].iloc[0, 0]
# 方法二:通过values提取
x = df.iloc[[0],[1]].values[0][0]
# 方法三:用squeeze压缩维度
x = df.iloc[[0],[1]].squeeze()

方法3:按列名提取(更直观)

直接使用loc方法,通过行索引和列名定位,同样能拿到纯字符串:

x = df.loc[0, 'Clue']
y = "The answer for: {} Crossword Clue.".format(x)

内容的提问来源于stack exchange,提问作者Navid Aslankhani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:15:55