python - 根据另一列中设置的金额向 pandas 列添加零

标签 python pandas

我有一列包含电话号码(作为字符串)。然后还有另一列为我提供了零的数量(作为 int),我想将其附加到现有的电话号码中。我想做的是(5 *“0”=>“00000”)。还有一个先决条件。如果电话号码以“1”结尾,则只能添加零。

Example:
>>> df = pd.DataFrame([["11", 2], ["21", 3], ["10", 6]], columns=['phone', 'ext_length'])

What I tried:
>>> df.loc[(df.phone.str.endswith("1")), "complete_phone"] = df.phone + (df.ext_length * "0")

在过滤电话以“1”结尾的正确行并创建“complete_phone”列有效时,我无法让“数学”工作。我正在得到

TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')

我既不理解错误消息,也不知道如何解决这个问题。

PS:我也在寻找一个链接,其中显示了如何正确包含 python 示例,正如我在其他问题中看到的 [in:] 和 [out:] 加上结果。有什么提示吗?

最佳答案

我认为你需要mask用于替换条件的 Truestr.repeat :

s = pd.Series(['0'], index=df.index)
mask = df.phone.str.endswith("1")
df["complete_phone"] = df.phone.mask(mask, df.phone + s.str.repeat(df.ext_length))
print (df)
  phone  ext_length complete_phone
0    11           2           1100
1    21           3          21000
2    10           6             10

另一个解决方案 DataFrame.apply :

mask = df.phone.str.endswith("1")
df["complete_phone"] = df['phone'].mask(mask, df.apply(lambda x: x['phone'] + 
                                                                 '0' * x.ext_length, axis=1))
print (df)
  phone  ext_length complete_phone
0    11           2           1100
1    21           3          21000
2    10           6             10
mask = df.phone.str.endswith("1")
df["complete_phone"] = df.phone.mask(mask, df['phone'] +
                                           df['ext_length'].apply(lambda x:'0'*x))
print (df)
  phone  ext_length complete_phone
0    11           2           1100
1    21           3          21000
2    10           6             10

您的解决方案类似,仅在掩码为 False 时才获取 NaN:

mask = df.phone.str.endswith("1")
df.loc[mask, "complete_phone"] = df['phone'] + df.apply(lambda x: '0' * x.ext_length, axis=1)
  phone  ext_length complete_phone
0    11           2           1100
1    21           3          21000
2    10           6            NaN

关于python - 根据另一列中设置的金额向 pandas 列添加零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44261535/

相关文章:

python - 安装 Pillow 时出错 --enable-jpeg 已请求但未找到 jpeg

python - 如何连接两个数据帧,但在发生冲突时仅从一个数据帧中获取值?

python - 如何强制IPython仅在所有线程完成后才给我一个新提示

python - MathJax SVG 未验证

Python Pandas : Why is numpy so much faster than Pandas for column assignment? 我可以进一步优化吗?

python - 无法执行基于时间的滚动操作窗口 Pandas ?始终给出窗口必须是整数

Python PANDAS 写入 csv : how to set decimal point (".", 或 ",")?

python - pandas:填充多个空数据框

python - 结合两个 Pandas 数据框添加相应的值

python - 如果您的代码隐藏运行无限循环,您如何获得响应式 GUI? PyQT