【发布时间】:2021-11-27 15:41:02
【问题描述】:
我想用 col2 替换 col1 元素。 例如,如果 col1 包含 abc,我想用 a{colb}c 替换它。
import pandas as pd
d = {'col1': ['a b', 'a c'], 'col2': ['z 26', 'y 25']}
df = pd.DataFrame(data=d)
print(df)
col1 col2
a b z 26
a c y 25
如果 df['col1']=='a b' 则需要输出
col1 col2 col3
0 a b z 26 a z
1 a c y 25 a c
我试过了
df['col3'] = np.where(df[df['col1']=='a b'],(df['col1'].replace(str(df['col1'].str.split(' ')[1])),(str(df['col2'].str.split(' ')[0]))), 0)
error: ---error: operands could not be broadcast together with shapes (1,3) (2,) ()
&
for x in df['col1']:
x.replace(df['col1'].str.split(' ')[1],df['col2'].str.split(' ')[1])
#error --replace() argument 1 must be str, not list
建议简单的解决方案...
【问题讨论】:
-
你的意思是
df["col1"].where(df["col1"].ne("a b"), df["col1"].str[0]+" "+df["col2"].str[0])?
标签: python pandas dataframe numpy for-loop