A B
0 2002-01-16 10
1 2002-01-16 7
2 2002-01-16 2
3 2002-01-16 8
4 2002-01-16 5
5 2002-01-17 54
6 2002-01-17 6
7 2002-01-17 2
I want to add a C column which contains the first Column B value for each Column A date group. The output might be:
A B C
0 2002-01-16 10 10
1 2002-01-16 7 10
2 2002-01-16 2 10
3 2002-01-16 8 10
4 2002-01-16 5 10
5 2002-01-17 54 54
6 2002-01-17 6 54
7 2002-01-17 2 54
I´ve tested with:
df["C"] = df.values[0][1]
But it doesn´t change the value for each Column A date group.
Thank you.
You can groupby column A, then use .transform('first')
on column B to generate a series that has the first value of the group for all items in the group, eg:
df.loc[:, 'C'] = df.groupby('A').B.transform('first')
This'll make your example frame be:
A B C
0 2002-01-16 10 10
1 2002-01-16 7 10
2 2002-01-16 2 10
3 2002-01-16 8 10
4 2002-01-16 5 10
5 2002-01-17 54 54
6 2002-01-17 6 54
7 2002-01-17 2 54
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加