首页 > 解决方案 > 使用 numpy 数组中的值从 DataFrame 创建 Pandas DataFrame 以访问数据框索引

问题描述

我有一个包含 40 个特征的 7000 行的大型数据集。我想使用原始行创建两个新数据框。我想使用一维 numpy 数组中的值选择哪些行进入哪个数据帧,然后将数组中的值与原始数据帧的索引进行比较,如果它们匹配,我想获取原始数据帧的整行和将其添加到新的数据框中。

#reading in my cleaned customer data and creating the original dataframe.
customer_data = pd.read_excel('Clean Customer Data.xlsx', index_col = 0)
#this is the 1D array that has a single element that corresponds to the index number of customer_data
group_list = np.array([2045,323,41,...,n])
# creating the arrays with a slice from group_list with the values of the row indexes for the groups
group_1 = np.array(group_list[:1972])
group_2 = np.array(group_list[1972:])
for X in range(len(group_list):
    i = 0
    #this is where I get stuck
    if group_1[i] == **the index of the original dataframe**
        group1_df = pd.append(customer_data)
    else:
        group2_df = pd.append(customer_data)
    i = i+1

显然,我正在做的事情有一些严重的语法问题,可能还有一些严重的逻辑问题,但是我已经用头撞墙了一个星期了,我的大脑一片混乱。

我期望发生的是原始数据框索引 2045 中的行将进入 group1_df。

最终,我希望创建两个具有与原始数据集相同特征的数据框(group1_df 和 group2_df),第一个有 1,972 条记录,第二个有 5,028 条记录。

数据集如下所示: 我正在使用的数据集的副本

标签: pythonarrayspandasdataframeindexing

解决方案


考虑DataFrame.reindex将每个组值与customer_data的索引对齐。

customer_data = pd.read_excel('Clean Customer Data.xlsx', index_col = 0)

group_list = np.array([2045,323,41,...,n])

group1_df = customer_data.reindex(group_list[:1972], axis = 'index')
group2_df = customer_data.reindex(group_list[1972:], axis = 'index')

推荐阅读