Python 熊猫:当单元格包含列表时,如何获得单元格中唯一的值数?
出于某种神秘的原因,我有一个看起来像Python 熊猫:当单元格包含列表时,如何获得单元格中唯一的值数?,python,pandas,Python,Pandas,出于某种神秘的原因,我有一个看起来像 index col_weird col_normal 2012-01-01 14:30 ['A','B'] 2 2012-01-01 14:32 ['A','C','D'] 4 2012-01-01 14:36 ['C','D'] 2 2012-01-01 14:39 ['E','B'] 4 2012-01-01 14:40 ['G','H'] 2 我想每5分钟对我的数据
index col_weird col_normal
2012-01-01 14:30 ['A','B'] 2
2012-01-01 14:32 ['A','C','D'] 4
2012-01-01 14:36 ['C','D'] 2
2012-01-01 14:39 ['E','B'] 4
2012-01-01 14:40 ['G','H'] 2
我想每5分钟对我的数据帧重新采样一次
- 获取
中所有列表中元素的唯一数量col\u
- 获取
col\u normal
resample().col\u-weird.nunique()
会失败,因为我需要唯一的元素数:也就是说,在14:30
和14:35
之间,我希望这个数字是4,对应于A、B、C、D
在同一时期,colu normal
的平均值当然是3
知道怎么弄到吗
谢谢 我想你可以先把
列表
扩展到系列
:
df = df['col'].apply(pd.Series).stack().reset_index(drop=True, level=1)
print (df)
2012-01-01 14:30 A
2012-01-01 14:30 B
2012-01-01 14:32 A
2012-01-01 14:32 C
2012-01-01 14:32 D
2012-01-01 14:36 C
2012-01-01 14:36 D
2012-01-01 14:39 E
2012-01-01 14:39 B
2012-01-01 14:40 G
2012-01-01 14:40 H
dtype: object
然后使用重新采样
:
df = df.resample('1H').nunique()
print (df)
2012-01-01 14:00:00 7
Freq: H, dtype: int64
按
pd.TimeGrouper('5Min')
分组,然后应用一个讨厌的函数
df.groupby(pd.TimeGrouper('5Min')).col.apply(lambda x: x.apply(pd.Series).stack().unique().shape[0])
index
2012-01-01 14:30:00 4
2012-01-01 14:35:00 4
2012-01-01 14:40:00 2
Freq: 5T, Name: col, dtype: int64
非常聪明,但是如果原始数据帧包含除
列以外的其他列怎么办?我想你可以对所有列设置索引,然后应用pd.Series
谢谢,伙计,但你的输出似乎不正确?@noobie再次修复了我的postthanks,但我不得不相信jezrael的答案。他在你面前给出了同样的解决方案。很抱歉bud@Noobienp jezrael岩石