【发布时间】:2021-01-09 14:26:23
【问题描述】:
我需要在DataFrameGroupBy 对象上使用slice。
例如,假设有DataFrame 和A-Z 列,如果我想使用列A-C 我将使用.loc[:, 'A':'C'],但是当我使用DataFrameGroupBy 时,我不能使用切片所以我必须写[['A', 'B', 'C']]
看这里:
from numpy import around
from numpy.random import uniform
from pandas import DataFrame
from string import ascii_lowercase
data = around(a=uniform(low=1.0, high=50.0, size=(6, len(ascii_lowercase) + 1)), decimals=3)
df = DataFrame(data=data, columns=['group'] + list(ascii_lowercase), dtype='float64')
rows, columns = df.shape
df.loc[:rows // 2, 'group'] = 1.0
df.loc[rows // 2:, 'group'] = 2.0
print(df)
abc = df.groupby(by='group')[['a', 'b', 'c']].shift(periods=1)
print(abc)
df 的输出是:
group a b c ... w x y z
0 1.0 22.380 36.873 10.073 ... 26.052 38.625 48.122 33.841
1 1.0 16.702 32.160 35.018 ... 12.990 17.878 19.297 16.330
2 1.0 9.957 25.202 7.106 ... 46.500 12.932 37.401 43.134
3 2.0 42.395 40.616 24.611 ... 30.436 33.521 42.136 2.690
4 2.0 2.069 29.891 2.217 ... 20.734 12.365 9.302 47.019
5 2.0 4.208 23.955 33.966 ... 45.439 16.488 32.892 9.345
abc 的输出是:
a b c
0 NaN NaN NaN
1 22.380 36.873 10.073
2 16.702 32.160 35.018
3 NaN NaN NaN
4 42.395 40.616 24.611
5 2.069 29.891 2.217
如何避免使用[['a', 'b', 'c']]?我有 105 列需要写在那里,我想使用像 .loc[:, 'a':'c'] 一样的切片
谢谢大家:)
【问题讨论】:
标签: python pandas pandas-groupby slice