python - 使用 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 条记录。
解决方案
考虑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')
推荐阅读
- javascript - 使用 AJAX 调用从 Php 查看 PDF
- php - 如何从响应中获取 GuzzleHttp 7.x 解析的请求 url
- git - 合并到功能分支时,Git 在主恢复提交中恢复
- xml - 将xml转换为没有soapEnvolpe和命名空间的xml,还使用xslt将命名空间添加到内部元素
- node.js - Node/React/Redux:在 Node 和 React 之间传递 api JSON 对象时遇到问题
- c# - 为什么 WPF 在添加行后不调整设置为自动宽度的列的大小?
- java - 如何以最小的交换成本使两个数组值具有相同的频率
- reactjs - 如何在 React Native 的事件处理函数中获取输入的最新值?
- mysql - 如何在长度mysql中捕获NULL值?
- html - 如何使用 CSS 调整图像大小以适合其容器