Mar*_*rkS 5 dataframe python-3.x pandas
我正在浏览从 PACKT 购买的视频包来学习 pandas。作者使用 jijna2 style() 来突出显示每列中的最大值。我很快发现我无法在 PyCharm 中使用该技术。所以我决定提取这些值。
我想做的是通过从具有 N 列的数据帧中提取行索引、列名称和最大列值来创建一个三列数据帧,然后创建新的数据帧。新的数据框将显示每一行(如果有联系则显示所有适当的行)、列以及该列中的最大值。
我创建了一个玩具数据框只是为了完成代码。
我的代码和输出如下,在最底部,是我真正想要的新数据框的样子。
我知道我正在使用打印语句。该代码是迄今为止我使用过的唯一可以在我打领带时正确拾取多行的代码。
我抓住了整行,但我不想要。我也不确定如何从提取的数据构建建议的新数据框。
import pandas as pd
raw_data = {
'dogs': [42, 39, 86, 15, 23, 57, 68, 81, 86],
'cats': [52, 41, 79, 80, 34, 47, 19, 22, 59],
'sheep': [62, 37, 84, 51, 67, 32, 23, 89, 73],
'lizards': [72, 43, 36, 26, 53, 88, 88, 34, 69],
'birds': [82, 35, 77, 63, 18, 12, 45, 56, 58],
}
df = pd.DataFrame(raw_data,
index=pd.Index(['row_1', 'row_2', 'row_3', 'row_4', 'row_5', 'row_6', 'row_7', 'row_8', 'row_9'], name='Rows'),
columns=pd.Index(['dogs', 'cats', 'sheep', 'lizards', 'birds'], name='animals'))
print(df)
print()
# Get a list of all columns names
cols = df.columns
print(cols)
print('*****')
for col in cols:
print((df[df[col] == df[col].max()]))
'''
animals dogs cats sheep lizards birds
Rows
row_3 86 79 84 36 77
row_9 86 59 73 69 58
animals dogs cats sheep lizards birds
Rows
row_4 15 80 51 26 63
animals dogs cats sheep lizards birds
Rows
row_8 81 22 89 34 56
animals dogs cats sheep lizards birds
Rows
row_6 57 47 32 88 12
row_7 68 19 23 88 45
animals dogs cats sheep lizards birds
Rows
row_1 42 52 62 72 82
'''
row_3 dogs 86
row_9 dogs 86
row_4 cats 80
row_8 sheep 89
row_6 lizards 88
row_7 lizards 88
row_1 birds 82
Run Code Online (Sandbox Code Playgroud)
用于numpy.where匹配maxes 的索引并DataFrame通过索引创建新的 - 如果性能在大型中很重要,则更好DataFrame:
c, r = np.where(df.eq(df.max()).T)
df = pd.DataFrame({'idx':df.index[r], 'cols':df.columns[c], 'vals': df.values[r, c]})
print(df)
idx cols vals
0 row_3 dogs 86
1 row_9 dogs 86
2 row_4 cats 80
3 row_8 sheep 89
4 row_6 lizards 88
5 row_7 lizards 88
6 row_1 birds 82
Run Code Online (Sandbox Code Playgroud)
另一个唯一的 pandas 解决方案,用于DataFrame.unstack按第一级GroupBy.transform比较max每组的值:
s = df.unstack()
df = s[s.groupby(level=0).transform('max').eq(s)].reset_index(name='vals')
print(df)
animals Rows vals
0 dogs row_3 86
1 dogs row_9 86
2 cats row_4 80
3 sheep row_8 89
4 lizards row_6 88
5 lizards row_7 88
6 birds row_1 82
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24174 次 |
| 最近记录: |