简体   繁体   中英

append pandas dataframe to column

I'm stuck and need some help. I have the following dataframe:

+-----+---+---+--+--+
|     | A | B |  |  |
+-----+---+---+--+--+
| 288 | 1 | 4 |  |  |
+-----+---+---+--+--+
| 245 | 2 | 3 |  |  |
+-----+---+---+--+--+
| 543 | 3 | 6 |  |  |
+-----+---+---+--+--+
| 867 | 1 | 9 |  |  |
+-----+---+---+--+--+
| 345 | 2 | 7 |  |  |
+-----+---+---+--+--+
| 122 | 3 | 8 |  |  |
+-----+---+---+--+--+
| 233 | 1 | 1 |  |  |
+-----+---+---+--+--+
| 346 | 2 | 6 |  |  |
+-----+---+---+--+--+
| 765 | 3 | 3 |  |  |
+-----+---+---+--+--+

Column A has repeating values as shown. What I want to do is every time I see the repeating value in Column AI want to append a new colum with the corresponding values from column B as column C as shown below:

+-----+---+---+-----+
|     | A | B | C   |
+-----+---+---+-----+
| 288 | 1 | 4 | 9   |
+-----+---+---+-----+
| 245 | 2 | 3 | 7   |
+-----+---+---+-----+
| 543 | 3 | 6 | 8   |
+-----+---+---+-----+
| 867 | 1 | 9 | 1   |
+-----+---+---+-----+
| 345 | 2 | 7 | 6   |
+-----+---+---+-----+
| 122 | 3 | 8 | 3   |
+-----+---+---+-----+
| 233 | 1 | 1 | NaN |
+-----+---+---+-----+
| 346 | 2 | 6 | NaN |
+-----+---+---+-----+
| 765 | 3 | 3 | NaN |
+-----+---+---+-----+

Thanks.

Assuming that val is one of the repeated values,

slice = df.loc[df.A == val, 'B'].shift(-1)

will create a one-column data frame with the values re-indexed to their new positions.

Since none of the re-assigned index values should be redundant, you can use pandas.concat to stitch the different slices together without fear of losing data. Then just attach them as a new column:

df['C'] = pd.concat([df.loc[df['A'] == x, 'B'].shift(-1) for x in [1, 2, 3]])

When the column is assigned, the index values will make everything line up:

A  B    C
0  1  4  9.0
1  2  3  7.0
2  3  6  8.0
3  1  9  1.0
4  2  7  6.0
5  3  8  3.0
6  1  1  NaN
7  2  6  NaN
8  3  3  NaN

Reverse the dataframe order, groupby transform it against shift function, and reverse it back:

df = df[::-1]
df['C'] = df.groupby(df.columns[0]).transform('shift')
df = df[::-1]
df

    A    B     C
0    1    4  9.0
1    2    3  7.0
2    3    6  8.0
3    1    9  1.0
4    2    7  6.0
5    3    8  3.0
6    1    1  NaN
7    2    6  NaN
8    3    3  NaN

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