iloc按编号下载列

2024-09-27 07:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想下载列号,例如1,3,2。在param.txt文件中,我只有这样一个条目

import pandas as pd 
import numpy as np

df = pd.read_csv('sample1.csv')

with open('param.txt') as f:
  s = f.read()

  b = df.iloc[:, [s]] 
  print(b.to_string(index=False))

当我开始写剧本的时候

raise IndexError(f".iloc requires numeric indexers, got {arr}")
IndexError: .iloc requires numeric indexers, got ['1,3,2']

如何简单地从这种形式转换为数字形式

谢谢你的帮助


Tags: csvimporttxtdfreadparamas形式
1条回答
网友
1楼 · 发布于 2024-09-27 07:26:42

假设f.read()返回“1,2,3”,这应该可以工作

import pandas as pd 
import numpy as np

df = pd.read_csv('sample1.csv')

with open('param.txt') as f:
  s = f.read() # Assuming this is a string such as "1,2,3"

  s = s.split(",") # Split string to list where there are commas ["1","2","3"]
  s = [int(x) for x in s] # Convert entries from string to int [1,2,3]

  b = df.iloc[:, s] # No need for brackets since s is already a list
  print(b.to_string(index=False))

相关问题 更多 >

    热门问题