Home > Net >  How to add flag to each entry in existing pandas dataframe
How to add flag to each entry in existing pandas dataframe

Time:10-28

Problem

Given this dataframe:

df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

what is the simplest route to this:

        0       1       2
0  (1, 0)  (2, 0)  (3, 0)
1  (4, 0)  (5, 0)  (6, 0)
2  (7, 0)  (8, 0)  (9, 0)

Considered Questions and Approaches

Is there a way to convert the existing dataframe to a dataframe of tuples?

I haven't found a way to do so, nor thought of a better alternative, so my current approach is to create a new df, replacing each entry with a tuple (entry, flag).

In order to do that I would like to copy or add the original df to a df with empty tuples (0, 0), to avoid manually iterating over and reformating each entry into the new df.

Note, I would like to add the flag to each entry, not each row, making this question different from Adding binary flag to pandas DataFrame.

CodePudding user response:

Update

Actually, it seems we need to make it a list since tuples are immutable

Simple use applymap (cell by cell):

>>> df.applymap(lambda x: [x, 0])
        0       1       2
0  [1, 0]  [2, 0]  [3, 0]
1  [4, 0]  [5, 0]  [6, 0]
2  [7, 0]  [8, 0]  [9, 0]

Or apply with a comprehension:

>>> df.apply(lambda x: [[i, 0] for i in x])
        0       1       2
0  [1, 0]  [2, 0]  [3, 0]
1  [4, 0]  [5, 0]  [6, 0]
2  [7, 0]  [8, 0]  [9, 0]
  • Related