如何使用自定义索引标签访问PANDAS DataFrame中的一行?

发布于 2025-01-30 03:33:09 字数 448 浏览 2 评论 0 原文

我已经创建了一个pandas dataframe来保存这样的数据:

TF_IDF = pd.DataFrame(index = vocab)
TF_IDF['0'] = 0

其中 vocab 是一系列字符串,因此每列的索引标签是相应的字符串,

所以当我打印它时,看起来像这样。 :

           0
life       0
math       0
student    0
experi     0
control    0
...       ..
slave      0
linga      0
31-32      0
democrat   0
unsustain  0

如何使用字符串以给定索引访问一行?

例如,如果我有字符串“数学”,一个人将如何使用索引标签“数学”访问值?

I've created a pandas dataframe to hold the data like so:

TF_IDF = pd.DataFrame(index = vocab)
TF_IDF['0'] = 0

where vocab is an array of strings, so the index label of each column is the corresponding string

so when I print it, it looks like this:

           0
life       0
math       0
student    0
experi     0
control    0
...       ..
slave      0
linga      0
31-32      0
democrat   0
unsustain  0

How would I access a row at a given index by using a string?

for example, if I have the string "math" how would one access the value using the index label "math"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许仙没带伞 2025-02-06 03:33:09

您应该使用 而不是链接索引(如在您的答案中),因为它效率更高,链式索引有时可以提高 setterwithCopy 警告(阅读更多在这里)。

要使用.loc,您将其称为下面:

df.loc[row_index(es), col_names]

以下是您的示例中的以下内容:

TF_IDF.loc['life', '0']

返回:

0

You should use .loc[] rather than chained indexing (as in your answer) as it's more efficient, and chained indexing can sometimes raise a SettingWithCopy warning (read more here).

To use .loc, you would call it like below:

df.loc[row_index(es), col_names]

Which would be the below in your example:

TF_IDF.loc['life', '0']

returns:

0
放手` 2025-02-06 03:33:09

tf_idf ['0'] ['life'] 会让您到达那里

,而不是删除问题,我将把它留下来,以防万一其他人也找不到答案

TF_IDF['0']['life'] will get you there

Instead of removing the question, I'll leave it up, just in case someone else also cant find the answer anywhere else online

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文