【问题标题】:How to split column element and replace by other column value in python dataframe?如何拆分列元素并用python数据框中的其他列值替换?
【发布时间】: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


【解决方案1】:

我不完全确定我已经理解你在这里想要做什么,但这可以满足你的要求:

for i, row in df2.iterrows():
    if row["col1"] == "a b":
         row["col1"] = "a " + row["col2"].split(" ")[0]

要逐行迭代数据框,请使用 iterrows,它返回一个 (index, row) 的元组。

EDIT 请注意,使用 this 就地修改是未定义的。如果不想直接使用row可以修改原来的df,如果需要的话:

df2["col1"][i] = row["col1"]

(修改后row。)

这完全不像熊猫,毫无疑问,有一种方法可以用 pandas 一步完成,但这种模式适用于任何东西。它是否比“矢量化”解决方案慢取决于 pandas 是如何实现 iterrowsloc 的。

请注意,条件——“a b”——在这里是硬编码的,这似乎是你想要的。

【讨论】:

【解决方案2】:
import pandas as pd
d = {'col1': ['a b', 'a c'], 'col2': ['z 26', 'y 25']}
df = pd.DataFrame(data=d)

解决方案 1:

df.loc[(df['col1'] == 'a b'), 'col3'] = df['col1'].str[0] + ' ' + df['col2'].str[0]
df['col3'].fillna(df['col1'], inplace=True)

解决方案 2:

condition = (df['col1'] == 'a b')
df['col3'] = np.where((df['col1'] == 'a b'), df['col1'].str[0] + ' ' + df['col2'].str[0], df['col1'])

【讨论】:

    【解决方案3】:

    虽然这很混乱,但我设法在一行中完成了。老实说,我不确定它是否完全符合您的要求,但如果需要,我可以帮您修改它。

    df['col3'] = [f'{i[1].col1.split()[0]} {i[1].col2.split()[0]}' if i[1].col1 == 'a b' else i[1].col1 for i in df.iterrows()]
    

    【讨论】:

      【解决方案4】:

      我找到了这样的方法:拆分两个列并加入它们。但是我正在寻找替换和插入

      df['col3'] = df['col1'].apply(lambda x:x.split(' ') [0]) +' '+ df['col2'].apply(lambda x:x.split(' ') [0])
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2018-02-23
      • 1970-01-01
      • 2020-03-29
      • 2014-02-06
      • 2020-10-21
      • 1970-01-01
      • 2020-09-15
      • 2023-01-24
      • 2019-09-18
      相关资源
      最近更新 更多