我想转换以下DataFrame:
Cat A Cat B Total points
0 20 30 50
1 25 35 60转入:
Cat Points Total points
0 A 20 50
1 A 25 60
2 B 30 50
3 B 35 60我试着回复我自己的帖子,但似乎没有用。所以我会修改我原来的帖子。将来我该如何回复评论呢?
回答你的问题:是的,是35而不是45
这是我的DataFrame:https://i.stack.imgur.com/OQ79p.png的屏幕截图
发布于 2022-08-18 12:35:34
您可以使用pd.melt来实现这一点。例如:
import pandas as pd
data = {'Cat A': [20, 25], 'Cat B': [30, 35], 'Total points': [50, 60]}
df = pd.DataFrame(data)
df_res = pd.melt(df, id_vars='Total points', value_vars=['Cat A','Cat B'], value_name='Points', var_name='Cat')
print(df_res)
Total points Cat Points
0 50 Cat A 20
1 60 Cat A 25
2 50 Cat B 30
3 60 Cat B 35要将其转换为所请求的特定表单(所需的df),您可以这样做:
df_res['Cat'] = df_res['Cat'].str.extract('\s(.*$)')
col_order = ['Cat', 'Points', 'Total points']
df_res = df_res.loc[:, col_order]
print(df_res)
Cat Points Total points
0 A 20 50
1 A 25 60
2 B 30 50
3 B 35 60https://stackoverflow.com/questions/73402924
复制相似问题