【问题标题】:How do i select a column without using indexing如何在不使用索引的情况下选择列
【发布时间】:2022-01-21 22:09:05
【问题描述】:
A B C
Africa 2 3
Singapore 2 3

在 df.values.tolist() 中运行 for col 后: 我明白了:

非洲 2 3

新加坡 2 3 . . .

要捕获每一列(例如 A 列的 2,2),我似乎无法将列名捕获为 col['A'] 因为它会给我一条错误消息“TypeError:列表索引必须是整数或切片,而不是 str"

相反,我必须使用 col[0] den 它会给我 2,2 。

还有其他方法可以编写 col['A'] 的脚本吗?只是为了可追溯性/更容易让审阅者看到我正在使用描述 A 提取列,而不必参考 df 并查看列 [0] 指的是什么

【问题讨论】:

  • df.info() 的输出是什么?
  • 您正在迭代一个列表,因为使用了这样的数字索引。您可能想遍历数据框本身
  • 嗨@sammywemmy 感谢您的帮助!你能详细说明一下吗?
  • Hey @Corralien RangeIndex: 5197 entries, 0 to 5196 Data columns (total 17 columns): # Column Non-Null Count Dtype --- - ----- -------------- ----- 0 country_name 5197 非空对象 1 行业组 5197 非空对象 2 abc 计数 5197 非空 int64 3 计数xyz 5195 非空 float64
  • 正如@sammywammy 所说,我认为您只需要:for col in df.columns: 然后在循环内只需print(df[col])

标签: python arrays pandas list indexing


【解决方案1】:

使用.to_dict('records')

a = pd.DataFrame({'A': [1, 2, 3], 'B': [10, 20, 30], 'C': [111, 222, 333]})
for col in a.to_dict('records'):
    print(f"{col['A']=}\t{col['B']=}\t{col['C']=}")

【讨论】:

  • 嘿!感谢您回来,我可能对我的 qns 不是很清楚,并添加了一些细节来澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多