python - 使用 numpy 数组中的值从 DataFrame 创建 Pandas DataFrame 以访问数据帧索引

标签 python arrays pandas dataframe indexing

我有一个包含 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 条记录。

数据集看起来像这样: Copy of the data set I'm working with

最佳答案

考虑 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/

相关文章:

python - 有哪些常用技术可以确保 TemplateView 的 get_context_data 中的代码逻辑被执行一次?

java - 方法 .toArray(IntFunction<A[]> Generator) 如何知道新数组的大小

python - Pandas 根据列计算顺序

pandas - 如何在matplotlib pandas中将两个文件的两个条形图组合在一张图中

python - 如何使用 Python pdblp 的 CSV 文件而不是股票引用来从 con.ref 获取 API

python - 如何从 CSV 导入中删除尾随空格?

arrays - 具有 O(n) 次反转的数组

java - 如何将 Vector 更改为 ArrayList?

python - 如何计算 Pandas 滚动窗口的累积乘积?

python - 使用 Python 的实时程序声音?