string - Pandas 通过查看两个列表是否具有共同值来累积计数
问题描述
如果我有这样的桌子
|---------------------|------------------|
| time | list of string |
|---------------------|------------------|
| 2019-06-18 09:05:00 | ['A', 'B', 'C']|
|---------------------|------------------|
| 2019-06-19 09:05:00 | ['A', 'C'] |
|---------------------|------------------|
| 2019-06-19 09:05:00 | ['B', 'C'] |
|---------------------|------------------|
| 2019-06-20 09:05:00 | ['C'] |
|---------------------|------------------|
| 2019-06-20 09:05:00 | ['A', 'B', 'C']|
|---------------------|------------------|
对于每一行,我想知道在当前时间戳之前有多少行对当前字符串列表具有至少一个公共值。
慢代码将是这样的:
results = [] for i in range(len(df)):
current_t = df['time'].iloc[i]
current_string = df['list_of_string'].iloc[i]
df_before_t = df[df['time']<current_t]
cumm_count = 0
for row in df_before_t['list_of_string']:
if (set(current_string) & set(row)):
cumm_count += 1
results.append(cumm_count)
所以结果表将是:
|---------------------|------------------|---------------------|
| time | list of string | result |
|---------------------|------------------|---------------------|
| 2019-06-18 09:05:00 | ['A', 'B', 'C']| 0 |
|---------------------|------------------|---------------------|
| 2019-06-19 09:05:00 | ['A', 'C'] | 1 |
|---------------------|------------------|---------------------|
| 2019-06-19 09:05:00 | ['D'] | 0 |
|---------------------|------------------|---------------------|
| 2019-06-20 09:05:00 | ['C'] | 2 |
|---------------------|------------------|---------------------|
| 2019-06-20 09:05:00 | ['A', 'B', 'C']| 2 |
|---------------------|------------------|---------------------|
我目前拥有的数据集比较大,我想获得帮助以快速处理这些数据。非常感谢!
解决方案
一种方法是将列表转换为集合并使用 listcomplist of string
并与time
那些小于当前的time
s = df['list of string'].map(set)
t = pd.to_datetime(df.time)
df['result'] = [sum(len(x & y) != 0 for y in s[t.iloc[i] > t])
for i,x in enumerate(s)]
Out[283]:
time list of string result
0 2019-06-18 09:05:00 [A, B, C] 0
1 2019-06-19 09:05:00 [A, C] 1
2 2019-06-19 09:05:00 [D] 0
3 2019-06-20 09:05:00 [C] 2
4 2019-06-20 09:05:00 [A, B, C] 2
推荐阅读
- apache-spark - Pyspark 收集/分组嵌套数据
- reactjs - 未选中框时更新状态
- python - Pandas DataFrame:如何删除列并对选定列执行计算
- c++ - 无法弄清楚为什么没有在 SDL 中绘制线
- javascript - 如何使用地图功能(ReactJS)限制购物车中的项目
- solr - solr:edismax tie 参数未按描述工作
- java - Spring-5 ResponseEntity(不存在创建者,如默认构造)
- jquery - 使用选择选项 rails 查询数据库
- python - 使用python将非固定文本文件转换为CSV
- python - 从 numpy 中的 beta 分布中采样随机数并将结果分配给 pandas 数据帧的切片 - SettingWithCopyWarning