【问题标题】:For i in list: -> accessing and using i to index into a pandas dataframe [duplicate]对于列表中的 i:-> 访问和使用 i 来索引 pandas 数据框 [重复]
【发布时间】:2023-03-08 21:14:02
【问题描述】:

所以我有 2 个数据集:1. 一个数据数组(称为 x),2. 一个带有 n 列的 pandas 数据框

我正在尝试编写一个 for 循环,该循环遍历我的 dataframe 中的每一列,并计算该列与我的第一个数据数组 x 的相关系数。

x = [1.2, 1.9, 2.2, 4.1]
y = {'col1': [1, 2, 3, 4], 'col2': [10, 20, 30, 40]}
example_df = pd.DataFrame(data = y)
for i in example_df.columns:
 print(np.corrcoef(x, example_df.i)[0, 1])

但是,我收到一个错误

"'DataFrame' 对象没有属性 'i'"

我想知道是否有人对如何访问和使用'i' 访问我的dataframe 中的列有任何建议。

【问题讨论】:

  • 如果i是一个变量,你需要使用df[i]

标签: python pandas for-loop


【解决方案1】:

当你写这个时:

example_df.i

...那是要求一个字面上名为i 的列。当然你也没有。

您有一个名为col1 的列,而i 是一个包含字符串'col1' 的变量。要提出这个要求,请执行以下操作:

example_df[i]

【讨论】:

  • 非常感谢,这帮助了很多人!干杯
猜你喜欢
  • 2016-11-10
  • 2020-10-21
  • 2013-11-26
  • 1970-01-01
  • 2011-07-24
  • 2018-02-07
  • 2018-09-10
  • 2021-01-29
  • 2018-03-12
相关资源
最近更新 更多