![](/img/trans.png)
[英]Pandas conditionally select column values based on data from other dataframe
[英]How to conditionally create pandas column from other column values
我有一個看起來像這樣的 dataframe:
word start stop speaker
0 but that's alright 2.72 3.47 2
1 we'll have to 8.43 9.07 1
2 okay sure 9.19 11.01 2
3 what? 11.02 12.00 1
4 I agree 12.01 14.00 2
5 but i disagree 14.01 17.00 2
6 thats fine 17.01 19.00 1
7 however you are 19.01 22.00 1
8 like this 22.01 24.00 1
9 and 24.01 25.00 1
我想創建兩個新列,df.speaker_1 和 df.speaker_2。 當 df.speaker == 2 時,我希望 df.speaker_2 包含 df.word 的值。 當 df.speaker,= 2. 我希望它包含一個空字符串。 對其他揚聲器值重復相同的操作:它應該如下所示:
word start stop speaker speaker_2 speaker_1
0 but that's alright 2.72 3.47 2 but that's alright
1 we'll have to 8.43 9.07 1 we'll have to
2 okay sure 9.19 11.01 2 okay sure
3 what? 11.02 12.00 1 what?
4 I agree 12.01 14.00 2 I agree
5 but i disagree 14.01 17.00 2 but i disagree
6 thats fine 17.01 19.00 1 thats fine
7 however you are 19.01 22.00 1 however you are
8 like this 22.01 24.00 1 like this
9 and 24.01 25.00 1 and
任何建議將不勝感激,謝謝。
您可以從列word
中復制值,然后根據需要替換為空字符串:
df['speaker_1'] = df['word']
df['speaker_2'] = df['word']
df.loc[df['speaker'] != 1, 'speaker_1'] = ''
df.loc[df['speaker'] != 2, 'speaker_2'] = ''
或者,您可以使用apply
,但我發現在您的情況下這更簡單。
您可以使用pd.DataFrame.mask()
:
df['speaker_1'] = df.word.mask(df.speaker!=1, '')
df['speaker_2'] = df.word.mask(df.speaker!=2, '')
# word start ... speaker_1 speaker_2
# 0 but that's alright 2.72 ... but that's alright
# 1 we'll have to 8.43 ... we'll have to
# 2 okay sure 9.19 ... okay sure
# 3 what? 11.02 ... what?
# 4 I agree 12.01 ... I agree
# 5 but i disagree 14.01 ... but i disagree
# 6 thats fine 17.01 ... thats fine
# 7 however you are 19.01 ... however you are
# 8 like this 22.01 ... like this
# 9 and 24.01 ... and
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.