python - Python如何通过名称或编号检查数据框中是否存在列
问题描述
我编写了一个函数,它询问用户列名(例如'Age')或列号(0、1、...或-1、-2、...)并在存在时返回它。我想知道我的解决方案是否可以在代码设计方面得到改进。
为了澄清,我需要这段代码用于另一个函数,该函数计算应该手动选择标签列的数据帧上的香农熵。
import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B':['a', 'b', 'c']})
def read(df):
while True:
column = input("Please, enter column name or number:")
if column.lstrip('-').isdecimal():
if (-df.shape[1] > int(column)) or (int(column) >= df.shape[1]):
print('Such column does not exist. Please, try again. \n')
continue
else:
return df.iloc[:, int(column)]
elif column not in df.columns:
print('Such column does not exist. Please, try again. \n')
continue
else:
return df.loc[:, column]
return data[column]
read(df)
解决方案
可用的列df.columns
可用于获取所需的数据。如果该列不在 中df.columns
,请尝试将其转换int
为索引df.columns
并使用异常处理程序来处理未命中。
import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B':['a', 'b', 'c']})
def read(df):
while True:
column = input("Please, enter column name or number:")
if column not in df.columns:
try:
column = df.columns[int(column)]
except (IndexError, ValueError):
print(f"Column {column!r} does not exist, Please try again.")
continue
break
return df.loc[:, column]
print(read(df))
推荐阅读
- go - 我想格式化一个整数数组。如何发送数组以便每个动词接收数组的不同元素?
- javascript - 将事件侦听器添加到动态添加的列表元素
- module - 使用来自另一个项目的组件和模块 angular5
- powershell - Invoke-WebRequest Links 属性值以 about:// 开头
- windows-installer - WPF 应用程序在我启动时崩溃
- excel - 有没有其他方法可以解析带有不规则表格的 Excel 文件?
- javascript - 如何通过 jQuery 的 $.ajax() 函数在 php 中传递数据值?
- c++ - 从二进制文件加载列表后,我的代码似乎进入了无限循环
- azure - 如何从 Azure 策略调用 REST 函数
- android - 如何从 JSON 文件添加图像 URL