我见过很多关于数据透视表的问题.即使他们不知道他们询问数据透视表,他们通常也是.几乎不可能写出一个规范的问题和答案,其中包含了旋转的所有方面....
......但是我要试一试.
现有问题和答案的问题在于,问题通常集中在OP难以概括以便使用一些现有的良好答案的细微差别.但是,没有一个答案试图给出全面的解释(因为这是一项艰巨的任务)
从我的谷歌搜索中查看一些示例
pd.DataFrame.pivot因此,每当有人搜索时,pivot他们会得到零星的结果,而这些结果可能无法回答他们的具体问题.
您可能会注意到,我明显地将我的列和相关列值命名为与我将如何在下面的答案中进行调整相对应.请注意,以便熟悉哪些列名称可以从哪里获得您正在寻找的结果.
import numpy as np
import pandas as pd
from numpy.core.defchararray import add
np.random.seed([3,1415])
n = 20
cols = np.array(['key', 'row', 'item', 'col'])
arr1 = (np.random.randint(5, size=(n, 4)) // [2, 1, 2, 1]).astype(str)
df = pd.DataFrame(
add(cols, arr1), columns=cols
).join(
pd.DataFrame(np.random.rand(n, 2).round(2)).add_prefix('val')
)
print(df)
key row item col val0 val1
0 key0 row3 item1 col3 0.81 0.04
1 key1 …Run Code Online (Sandbox Code Playgroud) 我在这里面临一些问题,在我的python包中我安装了numpy,但我仍然有这个错误'DataFrame'对象没有属性'sort'
任何人都可以给我一些想法..
这是我的代码:
final.loc[-1] =['', 'P','Actual']
final.index = final.index + 1 # shifting index
final = final.sort()
final.columns=[final.columns,final.iloc[0]]
final = final.iloc[1:].reset_index(drop=True)
final.columns.names = (None, None)
Run Code Online (Sandbox Code Playgroud) 我有一个csv格式的表,看起来像这样.我想转置表,以便指标名称列中的值是新列,
Indicator Country Year Value
1 Angola 2005 6
2 Angola 2005 13
3 Angola 2005 10
4 Angola 2005 11
5 Angola 2005 5
1 Angola 2006 3
2 Angola 2006 2
3 Angola 2006 7
4 Angola 2006 3
5 Angola 2006 6
Run Code Online (Sandbox Code Playgroud)
我希望最终结果像这样:
Country Year 1 2 3 4 5
Angola 2005 6 13 10 11 5
Angola 2006 3 2 7 3 6
Run Code Online (Sandbox Code Playgroud)
我尝试过使用pandas数据框并没有太大的成功.
print(df.pivot(columns = 'Country', 'Year', 'Indicator', values = 'Value'))
Run Code Online (Sandbox Code Playgroud)
有关如何实现这一点的任何想法?
谢谢
在pandas标签上,我经常看到用户询问有关在 pandas 中融合数据框的问题。我将尝试针对此主题进行规范的问答(自我回答)。
我要澄清:
什么是熔体?
我如何使用熔体?
我什么时候使用熔体?
我看到一些关于融化的热门问题,例如:
pandas 将一些列转换为行:这实际上可能很好,但更多的解释会更好。
Pandas Melt Function : Nice question answer是好的,但是有点太含糊了,没有太多的展开。
融化熊猫数据框:也是一个不错的答案!但这仅适用于特定情况,这很简单,仅pd.melt(df)
Pandas 数据框使用列作为行(融化):非常整洁!但问题是它仅适用于 OP 提出的特定问题,这也需要使用pivot_table。
所以我将尝试针对这个主题进行规范的问答。
我将在这个随机成绩数据集上为随机年龄的随机人提供我所有的答案(更容易解释答案:D):
import pandas as pd
df = pd.DataFrame({'Name': ['Bob', 'John', 'Foo', 'Bar', 'Alex', 'Tom'],
'Math': ['A+', 'B', 'A', 'F', 'D', 'C'],
'English': ['C', 'B', 'B', 'A+', 'F', 'A'],
'Age': [13, 16, 16, 15, 15, 13]})
>>> df
Name Math English Age
0 Bob A+ C 13
1 John …Run Code Online (Sandbox Code Playgroud) 我有一个pandas数据帧,有4行和4列 - 这里是简单的版本:
import pandas as pd
import numpy as np
rows = np.arange(1, 4, 1)
values = np.arange(1, 17).reshape(4,4)
df = pd.DataFrame(values, index=rows, columns=['A', 'B', 'C', 'D'])
Run Code Online (Sandbox Code Playgroud)
我想要做的是将其转换为2*8数据帧,每个数组都有B,C和D alligng - 所以它看起来像这样:
1 2
1 3
1 4
5 6
5 7
5 8
9 10
9 11
9 12
13 14
13 15
13 16
Run Code Online (Sandbox Code Playgroud)
阅读熊猫文档我试过这个:
df1 = pd.pivot_table(df, rows = ['B', 'C', 'D'], cols = 'A')
Run Code Online (Sandbox Code Playgroud)
但是给我一个错误,我无法确定来源(以...结尾)
DataError:无需聚合的数字类型
)
接下来我想基于A值拆分数据帧,但我认为.groupby命令可能会处理它
我创建了以下数据帧 df
col1 col2 col3
0 4 5 2
1 5 2 4
2 3 10 3
3 6 2 2
4 3 2 4
Run Code Online (Sandbox Code Playgroud)
我现在想要的是翻转行,以便df看起来像这样:
column_name value
0 col1 4
1 col2 5
2 col3 2
3 col1 5
4 col2 2
5 col3 4
... ... ...
Run Code Online (Sandbox Code Playgroud)
我想我需要使用stack(),但我不确定如何.我尝试了以下内容
df = df.stack().rename_axis(['column_name']).reset_index(name = 'value')
Run Code Online (Sandbox Code Playgroud)
但是会返回以下错误
raise ValueError('Length of names must match number of levels in '
ValueError: Length of names must match number of levels in MultiIndex. …Run Code Online (Sandbox Code Playgroud) 我有以下Python pandas数据帧:
id| country | 2016 | 2017 | 2018
--+----------+------+------+------
0 | saudi | A | null | B
1 | china | C | A | B
2 | pakistan | null | null | C
Run Code Online (Sandbox Code Playgroud)
我想要:
id| country | year | value
--+----------+------+------
0 | saudi | 2016 | A
1 | saudi | 2018 | B
2 | china | 2016 | C
3 | china | 2017 | A
4 | china | 2018 | …Run Code Online (Sandbox Code Playgroud) 我有一个如下形式的数据框:
basket fruit_apple fruit_pear fruit_cherry
basket_id_1 5 NaN 6
basket_id_2 NaN 1 NaN
Run Code Online (Sandbox Code Playgroud)
我想创建两个新列,应该如下所示:
basket fruit_type number
basket_id_1 apple 5
basket_id_1 pear NaN
basket_id_1 cherry 6
basket_id_2 apple NaN
basket_id_2 pear 1
basket_id_2 cherry NaN
Run Code Online (Sandbox Code Playgroud)
其中fruit_type 的内容是通过colname.split('_')[1]
如何以简洁的方式自动确定的?
pandas ×8
python ×8
dataframe ×5
group-by ×1
numpy ×1
pandas-melt ×1
pivot ×1
python-3.x ×1
transpose ×1