python - 用循环填充空数据框
问题描述
我有以下数据框
print(df.head(5))
date places_occupees
0 2017-01-01 00:00:00.0000000 238
1 2017-01-01 00:01:00.0000000 238
2 2017-01-01 00:02:00.0000000 238
3 2017-01-01 00:03:00.0000000 238
4 2017-01-01 00:04:00.0000000 238
5 2017-01-01 00:05:00.0000000 238
(请注意日期列类型为字符串)
我有一个字符串列表,用于对数据框中的数据进行排序。
print(list_holidays)
['2017-01-01', '2017-05-01', '2017-05-08', '2017-07-14', '2017-11-11', '2017-04-17', '2017-06-05', '2017-05-25', '2017-08-15', '2017-11-01', '2017-12-25']
然后我创建一个具有相同 2 列的新空数据框。我将使用循环用数据填充它:
new_df = pd.DataFrame(columns=['date', 'places_occupees'])
这是我使用的,但返回一个空数据框
for i in list_holidays:
filter = df[df['date'].str.contains(i)]
new_df['date'].append(filter.date)
new_df['places_occupes'].append(filer.places_occupees)
我想做的是用排序后获得的日期填充 new_df 'date' 列,并用排序后获得的值填充 new_df 'places_occupees' 列,这些值应该看起来像初始数据框但在应用过滤器之后。
解决方案
您可以将filter
结果(正确)保存在列表中,然后用于pd.concat
获取新的 df.
尝试这个:
filtered = []
for i in list_holidays:
filter = df[df['date'].str.contains(i)]
filtered.append(filter)
new_df = pd.concat(filtered)
print(new_df)
或使用简单的列表理解:
new_df = pd.concat([df[df['date'].str.contains(i)] for i in list_holidays])
print(new_df)
推荐阅读
- apache-spark - 在 pyspark 数据框中查找不重叠的窗口
- c# - 无法获取文本框以显示来自数据网格显示值的数据绑定的值
- spring-boot - 如何从命令行插入其他属性?
- javascript - 如果元素在数组中,则根据循环检查中锚项的 ID 检查数据 ID
- java - 需要使用 BooleanBuilder 连接多个数组值
- reactjs - 反应在生产中使用什么而不是代理?
- c# - 串行端口中并不总是检测到奇偶校验错误
- javascript - 动态生成的元素内的 JQuery 不运行
- python - 如何将 jupyter notebook 转换为没有单元格符号的 python 脚本?
- json - 在后端使用远程 JSON 填充 WordPress 高级自定义字段