用循环填充空数据框

时间:2019-07-16 09:51:04

标签: python pandas

我有以下数据框

// action files

export const getUsers = ()=> async dispatch =>{
    const usersResponse = await axios.get(users);
    const userData = usersResponse.data.result;
    dispatch({
        type: GET_USERS,
        payload: userData
    })
}

export const getAvailability = () => async dispatch =>{
    const availabilityResponse = await axios.get(availability);
    const availabilityData = availabilityResponse.data.result;
    dispatch({
        type: GET_AVAILABILITY,
        payload: availabilityData
    })
}


// reducers 

initial state = {
  getUsers: [],
  getAvailability: []
}

export default function(state = initialState, action) {
    switch (action.type) {
        case GET_USERS:
            return {
                ...state,
                getUsers: action.payload
            };
        case GET_AVAILABILITY:
            return {
                ...state,
                getAvailability: action.payload
            };
        default:
            return state;
    }
}


//component


  async componentDidMount() {
        await this.props.getUsers();
        await this.props.getAvailability();

        let availabilityObject = {};
        this.props.availability.map(availability => {
           availabilityObject[availability.uuid] = availability;
        });
        if (typeof this.props.users != "undefined") {
            this.props.users.map(user => {
                user.availability = availabilityObject[user.uuid];
            });
        }
          console.log(this.props.users) 
//this doesn't show a merged Object of users and availability
    }



    const mapStateToProps = (state) => ({
        users: state.getUsers,
        status: state.getAvailability
    });

(请注意日期列类型为字符串)

我有一个字符串列表,将用于对数据框中的数据进行排序。

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

然后我用相同的2列创建一个新的空数据框。我将使用循环将其填充数据:

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

这是我使用的内容,但返回一个空数据框

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

我想做的是用排序后获得的日期填充new_df'日期'列,并用排序后获得的值填充new_df'places_occupees'列,这些值看起来应该像初始数据帧,但是应用过滤器。

1 个答案:

答案 0 :(得分:1)

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