- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下数据框:
df = pd.DataFrame({'Date':['01/01/2021','08/01/2021'],
'a_score':[7,3],
'b_score':[2,4],
'a':['north','south'],
'b':['south','north']})
Date a_score b_score a b
01/01/2021 7 2 north south
08/01/2021 3 4 south north
我怎样才能最好地 reshape 它以将 a 列和 b 列中的数据堆叠在一起,并将 a_score 和 b_score 堆叠在一起?所需的输出如下所示:
Date Region score score_against
01/01/2021 north 7 2
01/01/2021 south 2 7
08/01/2021 north 4 3
08/01/2021 south 3 4
非常感谢
最佳答案
您可以获取内部 numpy 数组并对其进行操作以获得所需的结果:
import numpy as np
new_df = pd.DataFrame(np.vstack((df.values,df.values[:, [0,2, 1, 4,3]]))[:, :-1], columns = ['Date', 'score', 'score_against', 'Region'])
输出:
Date score score_against Region
0 01/01/2021 7 2 north
1 08/01/2021 3 4 south
2 01/01/2021 2 7 south
3 08/01/2021 4 3 north
解释:
np.vstack((df.values,df.values[:, [0,2, 1, 4,3]]))[:, :-1]
取内部 numpy 数组 (df.values) 交换列,然后将其与原始 numpy 数组垂直堆叠:
array([['01/01/2021', 7, 2, 'north'],
['08/01/2021', 3, 4, 'south'],
['01/01/2021', 2, 7, 'south'],
['08/01/2021', 4, 3, 'north']], dtype=object)
现在,您可以使用上面的
array
创建一个新的数据框。
new_df = new_df.sort_values('Date')
输出:
Date score score_against Region
0 01/01/2021 7 2 north
2 01/01/2021 2 7 south
1 08/01/2021 3 4 south
3 08/01/2021 4 3 north
关于python - 在将列与 Python Pandas 结合的同时 reshape (融化?)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67886244/
我有一个复杂的 melt 函数需要执行。我试过逐步解决它并检查其他问题,但我很困惑! 这是我当前的数据框: 1 2 4 5 6 10 24 Userid u_
我知道,这个问题已经被问过好几次了,但我没有设法根据已经问过的问题构建我的解决方案。 DF 我有: id| country | series name | 2015 | 2016 | 2017
我正在尝试从名为 df 的数据帧创建以下名为 out 的数据帧。我有一种非常手动且缓慢的方法,但我希望它可以通过 groupby() 和 melt() 的组合来完成 import pandas as
我有一个像这样的 pandas DataFrame: df = pd.DataFrame({'custid':[1,2,3,4], ...: 'prod1':['jeans','tshirt','ja
我有这样一个数据框 NSW VIC 0 6718023 5023203 1 6735528 5048207 2 6742690 5061266 3 6766133 50
给定一个如下形式的方形 pandas DataFrame: a b c a 1 .5 .3 b .5 1 .4 c .3 .4 1 upper triangle 怎么可能?被熔化得到如
我玩 pandas 是为了适应它,我问自己是否可以在 pandas 中使用 Melt 功能而不需要太多麻烦? 我正在使用相当著名的titanic.csv数据集。 titanic = pd.read_c
我有一个关于航类的数据集,我有兴趣找出乘坐同一航类的一对乘客坐在同一排。假设所有航类中只有 Row 是唯一的,这意味着如果第 1 行在 10 号航类中被占用,那么它就不能出现在 11 号航类中。 即。
考虑这个 Pandas 数据框: df = pd.DataFrame({ 'User ID': [1, 2, 2, 3], 'Cupcakes': [1, 5, 4, 2],
这是我导入的数据框的前几行的示例(在完整数据集中,主题变量共有五个级别/因子,另外两个是代数 II 和几何)。 SID firstName lastName subject su
我有以下数据框: df = pd.DataFrame({'Date':['01/01/2021','08/01/2021'], 'a_score':[7,3],
我是一名优秀的程序员,十分优秀!