【问题标题】:Pandas - Access a value in Column B based on a value in Column APandas - 根据 A 列中的值访问 B 列中的值
【发布时间】:2019-08-28 06:54:48
【问题描述】:

所以我有一小部分数据,TFR.csv 采取以下形式:

Year     State1     State2     State3
1993       3          4           5
1994       6          2           1.4
...

我应该确定状态 2 的值何时处于最低值(1994 年),并提取状态 3 在当年 (1.4) 的任何值。

为此,我编写了一个简短的过滤器:

State1Min = min(TFR['State1']) #Determine the minimum value for State1

filt = (TFR['State1']==State1Min) #Filter to select the row where the value exists

TFR[filt]['State3'] #Apply this filter to the original table, and return the value in the State3 column.

它返回我正在寻找的正确值,而且还返回前面的行号:

2     1.4
Name: NT, dtype: float64

我需要打印这个值 1.4,所以我试图找到一种方法从这个输出中提取它。

感谢您的帮助。

【问题讨论】:

  • @Chris 下面的答案是最好的,但你也可以添加....TFR[filt]['State3'].values[0]
  • @run-out 非常感谢,成功了!克里斯的回答也有效,但我还没有达到我遇到这些功能的水平,因为我现在只是一个初学者!

标签: python python-3.x pandas dataframe jupyter-notebook


【解决方案1】:

使用pandas.DataFrame.set_indexidxmin

df = df.set_index('Year')
df.loc[df['State2'].idxmin(), 'State3']

输出:

1.4

【讨论】:

  • 非常感谢!我最终在评论中使用了上面列出的一种方法,因为我只是一个初学者,所以我的速度更快,但是你给了我关于如何继续学习语言的指示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2018-08-06
  • 2022-07-04
  • 1970-01-01
  • 2019-11-13
  • 2022-01-03
  • 2021-04-05
相关资源
最近更新 更多