gpt4 book ai didi

python - 根据 Pandas 中的第四列将数据从一列移动到另外两列中的一列

转载 作者:行者123 更新时间:2023-11-28 22:23:26 37 4
gpt4 key购买 nike

所以在 Pandas 中我有以下数据框

A B C D
0 X
1 Y
0 Y
1 Y
0 X
1 X

我想根据 B 将 A 中的值移动到 C 或 D。输出应该是这样的;

A B C D
0 X 0
1 Y 1
0 Y 0
1 Y 1
0 X 0
1 X 1

我试过使用多个 where 语句,例如

df['C'] = np.where(str(df.B).find('X'), df.A, '')
df['D'] = np.where(str(df.B).find('Y'), df.A, '')

但这会导致;

A B C D
0 X 0 0
1 Y 1 1
0 Y 0 0
1 Y 1 1
0 X 0 0
1 X 1 1

所以我猜它正在检查该值是否完全存在于列中,这是有道理的。我需要逐行迭代吗?

最佳答案

不要使用 find 转换为 str,因为它返回标量并且 0 被转换为 False 和另一个True 的整数:

print (str(df.B).find('X'))
5

最简单的是比较 bool 值 Series:

print (df.B == 'X')
0 True
1 False
2 False
3 False
4 True
5 True
Name: B, dtype: bool

df['C'] = np.where(df.B == 'X', df.A, '')
df['D'] = np.where(df.B == 'Y', df.A, '')

另一种解决方案 assign + where :

df = df.assign(C=df.A.where(df.B == 'X', ''),
D=df.A.where(df.B == 'Y', ''))

如果需要检查子串使用str.contains :

df['C'] = np.where(df.B.str.contains('X'), df.A, '')
df['D'] = np.where(df.B.str.contains('Y'), df.A, '')

或者:

df['C'] = df.A.where(df.B.str.contains('X'), '')
df['D'] = df.A.where(df.B.str.contains('Y'), '')

全部返回:

print (df)
A B C D
0 0 X 0
1 1 Y 1
2 0 Y 0
3 1 Y 1
4 0 X 0
5 1 X 1

关于python - 根据 Pandas 中的第四列将数据从一列移动到另外两列中的一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47011764/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com