Skip to content Skip to sidebar Skip to footer

How To Label Same Pandas Dataframe Rows?

I have a large pandas dataframe like this: log apple watermelon orange lemon grapes 1 1 1 yes 0 0 1 2 0 1 0 0 1

Solution 1:

Given

x = io.StringIO("""log  apple   watermelon  orange  lemon  grapes

1      1         1         yes     0      0
1      2         0         1       0      0
1     True       0         0       0      2
2      0         0         0       0      2
2      1         1         yes     0      0
2      0         0         0       0      2
2      0         0         0       0      2
3     True       0         0       0      2
4      0         0         0       0      2.1
4      0         0         0       0      2.1""")
df2 = pd.read_table(x, delim_whitespace=True)

You can first use transform with tuple to make each row hashable and comparable, and then play with indexes and range to create unique ids

f = df2.transform(tuple,1).to_frame()
k = f.groupby(0).sum()
k['id'] = range(1,len(k.index)+1)

And finally

df2['temp_key'] = f[0]
df2 = df2.set_index('temp_key')
df2['id'] = k.id
df2.reset_index().drop('temp_key', 1)

    log     apple   watermelon  orange  lemon   grapes  id
0   1       1       1           yes     0       0.0     1
1   1       2       0           1       0       0.0     2
2   1       True    0           0       0       2.0     3
3   2       0       0           0       0       2.0     4
4   2       1       1           yes     0       0.0     5
5   2       0       0           0       0       2.0     4
6   2       0       0           0       0       2.0     4
7   3       True    0           0       0       2.0     6
8   4       0       0           0       0       2.1     7
9   4       0       0           0       0       2.1     7

Post a Comment for "How To Label Same Pandas Dataframe Rows?"