【发布时间】:2020-12-18 08:28:57
【问题描述】:
每次 text_y 列中的值发生变化时,我需要遍历我的数据框行并将单列 bounding_box_y 旋转为 8 列。
原始数据框
所需的数据帧
任何人都可以帮助一些不会将值硬编码到代码中的代码吗?整个数据框超过 6000 行。每次另一列中的值发生变化时,我都需要将一列转为 8。
谢谢!
【问题讨论】:
标签: python-3.x pandas dataframe pandas-groupby pivot-table
每次 text_y 列中的值发生变化时,我需要遍历我的数据框行并将单列 bounding_box_y 旋转为 8 列。
原始数据框
所需的数据帧
任何人都可以帮助一些不会将值硬编码到代码中的代码吗?整个数据框超过 6000 行。每次另一列中的值发生变化时,我都需要将一列转为 8。
谢谢!
【问题讨论】:
标签: python-3.x pandas dataframe pandas-groupby pivot-table
请尝试将您的数据包含为可调用代码,以便其他人可以轻松复制/粘贴和实验。在您的情况下,您可以使用df.head(16).to_dict('list') 获得它。我用了以下
df = pd.DataFrame({
'boundingBox_y': [183, 120, 305, 120, 305, 161, 182, 161, 318, 120, 381, 120, 382, 162, 318, 161],
'text_y': (['FORM'] * 8) + (['ABC'] * 8),
'confidence': ([0.987] * 8) + ([0.976] * 8)
})
然后您可以pivot 您的数据框,但您需要添加一个新列来保存旋转后的列名称。
# rename the current values column
df.rename({'boundingBox_y': 'value'}, axis=1, inplace=True)
# create a column that contains the columns headers and can be pivoted
df['boundingBox_y'] = df.groupby(['confidence', 'text_y']).transform('cumcount')
# pivot your df
df = df.pivot(index=['confidence', 'text_y'],
columns='boundingBox_y', values='value')
输出
boundingBox_y 0 1 2 3 4 5 6 7
confidence text_y
0.976 ABC 318 120 381 120 382 162 318 161
0.987 FORM 183 120 305 120 305 161 182 161
【讨论】:
transform 行将根据需要创建尽可能多的 id,因此您的数据中可能有超过 8 列...您尝试过吗?如果不是您期望的结果,请编辑您的问题并使用此代码和完整数据显示结果,并说明需要改进的地方