简体   繁体   English

用循环填充空数据框

[英]Filling empty dataframe with loop

I have the following dataframe我有以下数据框

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

(please note that the date column type is string) (请注意日期列类型为字符串)

I have a list of strings that I will use to sort data in the dataframe.我有一个字符串列表,可用于对数据框中的数据进行排序。

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']

then I create a new empty dataframe with the same 2 columns.然后我创建一个具有相同 2 列的新空数据框。 I will fill it with data using the loop:我将使用循环用数据填充它:

new_df = pd.DataFrame(columns=['date', 'places_occupees'])

Here is what I used but returns an empty dataframe这是我使用的但返回一个空的数据框

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)

What I would like to do is to fill the new_df 'date' column with the dates obtained after sorting and to fill the new_df 'places_occupees' column with the values obtained after sorting that should look like the initial dataframe but after applying a filter.我想要做的是用排序后获得的日期填充 new_df 'date' 列,并用排序后获得的值填充 new_df 'places_occupees' 列,该值应该看起来像初始数据框,但在应用过滤器之后。

you can save your filter results (which are correct) in a list, then use pd.concat to get the new df.您可以将filter结果(正确)保存在列表中,然后使用pd.concat获取新的 df。

try this:尝试这个:

filtered = []
for i in list_holidays:
    filter = df[df['date'].str.contains(i)]
    filtered.append(filter)

new_df = pd.concat(filtered)

print(new_df)

or with a simple list-comprehension:或使用简单的列表理解:

new_df = pd.concat([df[df['date'].str.contains(i)] for i in list_holidays])

print(new_df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM