编辑:感谢您解释您的目标是什么。如果您的数据框中只有几个条目,您可以执行以下操作:
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)