简体   繁体   中英

Generate an edge list from a pandas dataframe

Suppose I have a pandas dataframe like this:

    Fruit_1   Fruit_2  Fruit_3 
0   Apple     Orange   Peach 
1   Apple     Lemon    Lime
2   Starfruit Apple    Orange 

Reproducible form:

df = pd.DataFrame([['Apple', 'Orange', 'Peach'],
                   ['Apple', 'Lemon', 'Lime'],
                   ['Starfruit', 'Apple', 'Orange']],
                  columns=['Fruit_1', 'Fruit_2', 'Fruit_3'])

I want to generate an edge list, which consists of:

Apple, Orange
Apple, Peach
Orange, Peach
Apple, Lemon
Apple, Lime
Lemon, Lime
Starfruit, Apple
Starfruit, Orange
Apple, Orange

How do I do it in Python?

I don't know pandas but you could use itertools.combinations on the rows

itertools.combinations(row, 2)

this creates an iterator which you can simply convert to a list of pairs.

Joining these lists after collecting them into a list can be done using a flat list comprehension

[pair for row in collected_rows for pair in row]

Or use the typically much faster numpy way

data[:, np.c_[np.tril_indices(data.shape[1], -1)]]

If you want a flat list

data[:, np.c_[np.triu_indices(data.shape[1], 1)]].reshape(-1,2)

Note that triu_indices lists the vertices in order while tril_indices lists them the other way round. They are normally used to get the indices of the upper or lower triangle of a matrix.

Here is a Pandas solution:

In [118]: from itertools import combinations

In [119]: df.apply(lambda x: list(combinations(x, 2)), 1).stack().reset_index(level=[0,1], drop=True).apply(', '.join)
Out[119]:
0        Apple, Orange
1         Apple, Peach
2        Orange, Peach
3         Apple, Lemon
4          Apple, Lime
5          Lemon, Lime
6     Starfruit, Apple
7    Starfruit, Orange
8        Apple, Orange
dtype: object

I might be a little late for this post,but recently I had the necessity to do exactly what you are asking. I managed to avoid the usage of itertools with something of this kind. If this is your DataFrame:

df = pd.DataFrame([['Apple', 'Orange', 'Peach'],
               ['Apple', 'Lemon', 'Lime'],
               ['Starfruit', 'Apple', 'Orange']],
              columns=['Fruit_1', 'Fruit_2', 'Fruit_3'])

you simply call a function:

>>> edgelist = get_edgelist(df)

      ID1        ID2
0   Apple     Orange
1   Apple      Peach
2  Orange      Peach
3   Apple      Lemon
4   Apple       Lime
5   Lemon       Lime
6   Apple     Orange
7   Apple  Starfruit
8  Orange  Starfruit

defined as:

def fast_combinations(row : list, self_loops = False) -> np.array:    
    
try:

        if self_loops:

            comb = np.unique(np.sort(np.array(np.meshgrid(row, row)).T.reshape(-1,2)), axis=0)

        else:
            
            comb = np.unique(np.sort(np.array(np.meshgrid(row, row)).T.reshape(-1,2)), axis=0)
            comb = np.delete(comb, np.where(comb[:,0] == comb[:,1]), axis=0)

        return comb

    except:

        return [[None, None]]


def get_edgelist(df, **kwargs):

    cols = df.columns
    df['combined'] = df[df.columns].values.tolist()

    # Clear space
    df.drop(cols, axis=1, inplace=True)

    arrays = []


    for row in range(len(df.index)):

        arrays.append(fast_combinations(df.loc[row, 'combined'], kwargs))

    return pd.DataFrame(np.concatenate( arrays, axis=0 ), columns=['ID1', 'ID2']).replace('nan', None).dropna().reset_index(drop=True)

I removed the descriptions from the functions to make it easier to read, but you can find them here https://gist.github.com/Stefano314/607db3ffc53d680d60de61d09ca39a08 .

I used this on a 2.5 milion rows dataframe, from which I got 45 milions associations, and it took me ~48 minutes on an i7-3770.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM