在使用 Pandas 处理和操作数据帧方面,我目前面临着一个我似乎无法解决的问题。
为了让您了解我正在谈论的数据帧以及您将在我的代码中看到的数据:
我正在尝试将数据集“data”的“exercise”列中的词更改为数据集“exercise”的“name”列中的词。
例如,“data”数据集的“exercise”列中的首字母缩写“Dl”应更改为“exercise”数据集“name”列中的“Dead Lifts”。
我尝试了很多方法,但似乎都失败了。我每次都收到同样的错误。
这是我尝试过的方法的代码:
### Method 1 ###
# Rename Name Column in 'exercise'
exercise = exercise.rename(columns={'label': 'exercise'})
# Merge Exercise Columns in 'exercise' and in 'data'
data = pd.merge(data, exercise, how = 'left', on='exercise')
### Method 2 ###
data.merge(exercise, left_on='exercise', right_on='label')
### Method 3 ###
data['exercise'] = data['exercise'].astype('category')
EXERCISELIST = exercise['name'].copy().to_list()
data['exercise'].cat.rename_categories(new_categories = EXERCISELIST, inplace = True)
### Same Error, New dataset ###
# Rename Name Column in 'area'
area = area.rename(columns={'description': 'area'})
# Merge Exercise Columns in 'exercise' and in 'data'
data = pd.merge(data, area, how = 'left', on = 'area')
这是我得到的错误:
<块引用>回溯(最近一次调用最后一次):
文件“---”,第 232 行,
data.to_frame().merge(exercise, left_on='exercise', right_on='label')
文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/frame.py”,第8192行,合并
返回合并(
文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/reshape/merge.py”,第74行,合并
op = _MergeOperation(
文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/reshape/merge.py”,第 668 行,init
) = self._get_merge_keys()
文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/reshape/merge.py”,第1046行,_get_merge_keys
left_keys.append(left._get_label_or_level_values(lk))
文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/generic.py”,第1683行,_get_label_or_level_values
引发 KeyError(key)
关键错误:'锻炼'
有人能帮我解决这个问题吗?预先非常感谢您。
答案 0 :(得分:1)
area = pd.DataFrame({"arealabel":["AGI","BAL"],
"description":["Agility","Balance"]})
exercise = pd.DataFrame({"description":["Jump rope","Dead lifts"],
"label":["Jr","Dl"]})
data = pd.DataFrame({"exercise":["Dl","Dl"],
"area":["AGI","BAL"],
"level":[0,3]})
(data.merge(area, left_on="area", right_on="arealabel")
.drop(columns=["arealabel","area"])
.rename(columns={"description":"area"})
.merge(exercise, left_on="exercise", right_on="label")
.drop(columns=["exercise","label"])
.rename(columns={"description":"exercise"})
)
level | 区域 | 运动 | |
---|---|---|---|
0 | 0 | 敏捷 | 死车 |
1 | 3 | 平衡 | 死车 |