首页 > 解决方案 > 用循环填充空数据框

问题描述

我有以下数据框

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' 列,这些值应该看起来像初始数据框但在应用过滤器之后。

标签: pythonpandas

解决方案


您可以将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)

推荐阅读