我有一个包含 40 个特征的 7000 行的大型数据集。我想用原始行创建两个新数据框。我想使用 1D 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 条记录。
最佳答案
考虑 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')
关于python - 使用 numpy 数组中的值从 DataFrame 创建 Pandas DataFrame 以访问数据帧索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57022264/