根据条件移动数据帧中的记录

2024-06-16 10:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力改变熊猫唱片公司在特定条件下的立场。 我想做的是将在其before_id(包括String)列中有值的每一行移动到另一行的下一个索引位置,该行在node_id(包括String)中的值与其相同。 我的代码并没有像我期望的那样工作。它没有返回任何错误,但根本没有对它们进行排序

不过我有点担心我的解释。。。。 你有什么办法来达到这个目的吗??还是在熊猫身上做不到

client_data = """node_id,option,before_id
    1aa,A,
    8xyz,C,2aa
    2aa,A,1aa
    5mm,A,4bb
    4bb,C,8xyz
    6ccc,5mm,
    7,C,6ccc       
    """


df = pd.read_csv(io.StringIO(client_data), dtype='string', error_bad_lines=False)
    before = pd.notnull(df['before_id'])
    for ind,row in df.iterrows():
        if pd.notnull(row[2]):
            before_id = row[2]
            before_ind = df.index[df['node_id']==before_id]
            next_ind = before_ind + 1
            row.reindex(index=next_ind)
        else:
            pass
df

node_id,option,before_id
1aa,A,
8xyz,C,2aa
2aa,A,1aa
5mm,A,4bb
4bb,C,8xyz
6ccc,5mm,
7,C,6ccc


ideal output 

node_id,option,before_id
1aa,A,
2aa,A,1aa
8xyz,C,2aa
4bb,C,8xyz
5mm,A,4bb
6ccc,5mm,
7,C,6ccc

Tags: clientidnodedfdatastringindexnext
1条回答
网友
1楼 · 发布于 2024-06-16 10:28:56

似乎您正在尝试解决深度优先搜索图问题。 下面的解决方案是使用networkx图形库

import pandas as pd
import io

x = '''node_id,option,before_id
1aa,A,
8xyz,C,2aa
2aa,A,1aa
5mm,A,4bb
4bb,C,8xyz
6ccc,5mm,
7,C,6ccc'''

df = pd.read_csv(io.StringIO(x))
print("Original\n",df)
print('       \n')

import networkx as nx
G = nx.from_pandas_edgelist(df, 'before_id', 'node_id', 'option')
sortedNodes = [n[1] for n in list(nx.dfs_edges(G))]

df.node_id = df.node_id.astype('category')
df.node_id.cat.set_categories(sortedNodes, inplace=True)
df = df.sort_values(['node_id'])
print("Node-sorted\n",df)

输出:

Original
   node_id option before_id
0     1aa      A       NaN
1    8xyz      C       2aa
2     2aa      A       1aa
3     5mm      A       4bb
4     4bb      C      8xyz
5    6ccc    5mm       NaN
6       7      C      6ccc
       

Node-sorted
   node_id option before_id
0     1aa      A       NaN
2     2aa      A       1aa
1    8xyz      C       2aa
4     4bb      C      8xyz
3     5mm      A       4bb
5    6ccc    5mm       NaN
6       7      C      6ccc

相关问题 更多 >