gpt4 book ai didi

python - 从 Pandas DataFrame 返回单个单元格值

转载 作者:太空狗 更新时间:2023-10-29 22:25:51 27 4
gpt4 key购买 nike

我想问一个关于这个线程的扩展问题:

Select rows from a DataFrame based on values in a column in pandas .

下面列出了该线程的代码:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14

print(df.loc[df['D'] == 14])

这将产生以下结果:

   A    B      C   D
7 foo three 7 14

根据上面的代码,我怎样才能返回单个“值”而不是一行。也就是说,如何返回值 '7' 或值 'foo' 而不是整行?

最佳答案

@JonahWilliams 很接近,这是一个工作的:

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})

print(df.loc[df['D'] == 14]['A'].index.values)

>>>[7]

print(df.loc[df['D'] == 14]['A'].values)

>>>['foo']

关于python - 从 Pandas DataFrame 返回单个单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33027643/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com