在Python中,如果不满足条件,如何将一列中的值替换为另一列中的值

xvw2m8pv  于 2023-01-14  发布在  Python
关注(0)|答案(2)|浏览(144)

我有一些不一致的数据与5列。这两个我的重点是-"帐户名称"和"用户ID"。所有帐户名称应包含一个7字符串。如果没有,我想取代如果与ID在"用户ID"。示例数据:
| 账户名称|用户ID|
| - ------|- ------|
| 京邦05737|京邦05737|
| 博客@***. com|苯甲酰胺49568|
| 编号GV95577|编号GV95577|
我想得到:
| 账户名称|用户ID|
| - ------|- ------|
| 京邦05737|京邦05737|
| 苯甲酰胺49568|苯甲酰胺49568|
| 编号GV95577|编号GV95577|
我已经尝试了以下代码,并得到错误:
Reports.loc[Reports['Account Name'].astype(str).map(len) != 7] = Reports[Reports['User ID']].astype(str)
Reports.loc[Reports['Account Name'].astype(str).map(len) != 7].replace(Reports['User ID'])

if (Reports.loc['Account Name'].map(len) != 7):
        Reports.loc[i, 'Account Name']==Reports.loc[i, 'User ID']```

```Reports.loc[Reports['Account Name'].map(len) != 7, 'Account Name] = Reports.loc[Reports['Account Name'].map(len) != 7,'User ID']```

The errors have included: shape errors, invalid syntax, ...not in index

Any suggestions?
5f0d552i

5f0d552i1#

像这样的事。

for col1, id in df.itertuples(index=False):
  print("Iterating both columns:\n",a, b)
  if len(id) > 7:
    df['col1'].replace('col1', 'id')
fiei3ece

fiei3ece2#

这个代码对我很有效
Reports['Account Name']=Reports['User ID'].where(Reports['Account Name'].map(len)>7,Reports['User ID'])

相关问题