python - 使用字符串格式的 DataFrame 索引作为类的实例
问题描述
创建 DataFrame 和类后,我想将索引用作创建类的实例。听起来很奇怪,但让我解释一下:D
例如,我有这个 Dataframe df
:
Name 'Jane' 'Max'
Age 25 20
theName
和 theAge
是字符串类型的索引。我想将它转换为一个对象,以便我可以将它用作“I_am_a_class”类的实例,如下所示:
df.index[0]
output: 'Name'
df.index[0] = I_am_a_class(attributes)
df.index[1] = I_am_a_class(attributes)
这不起作用,因为它df.index[0]
是字符串格式。我想知道是否有办法将其转换df.index
为适当的格式,以便实现这一点?
解决方案
编辑:感谢您解释您的目标是什么。如果您的数据框中只有几个条目,您可以执行以下操作:
import pandas as pd
class legend():
def __init__(self,unit,meaning):
self.unit= unit
self.meaning= meaning
df = pd.DataFrame(
data = {
'unit':['m/s','Pa'],
'meaning':['distance moved divided by the time','force divided by the area'],
},
index=['velocity','pressure'],
)
velocity = legend(df.loc['velocity','unit'], df.loc['velocity','meaning'])
pressure = legend(df.loc['pressure','unit'], df.loc['pressure','meaning'])
print(velocity.unit)
print(velocity.meaning)
如果您在数据框中有太多或可变数量的行,因此您不能像上面那样手动制作变量,并且如果您出于某种原因真的不想使用字典,那么您可以执行以下,但不赞成:
import pandas as pd
class Legend():
def __init__(self,unit,meaning):
self.unit= unit
self.meaning= meaning
df = pd.DataFrame(
data = {
'unit':['m/s','Pa'],
'meaning':['distance moved divided by the time','force divided by the area'],
},
index=['velocity','pressure'],
)
#If you REALLY don't want to use a dictionary you can use exec to create arbitrary variable names
#This is bad practice in python. You can read more about it at the link below
#https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-via-a-while-loop
for i,r in df.iterrows():
exec('{} = Legend("{}","{}")'.format(i,r['unit'],r['meaning']))
print(velocity.unit)
print(velocity.meaning)
推荐阅读
- android - 在颤振应用程序中更新外部资产可写数据库
- azure - Azure Cosmos DB SQL API - 读取/查询具有未知数据结构的文档
- r - 如何将图形中的颜色顺序与 R 中的代码完全匹配?
- r - 关于将比例转换为百分比的快速问题 - R 中的森林函数
- sql - SQL - 使用 'HAVING' 和 'EXISTS' 而不使用 'GROUP BY'
- c++ - 带有模板成员函数和 std::invocable 的 C++20 概念中的错误
- aws-cli - 使用 Amazon SageMaker Studio Image Build CLI 从 Studio 笔记本构建容器映像
- javascript - 如何按键减少和求和嵌套对象数组
- javascript - React - 更改组件内的 defaultValue 输入
- serialization - Telethon - 如何序列化消息中的文件以便稍后发送?