小编hig*_*ife的帖子

Pandas - 根据条件将值从一行复制到另一行

给出的是以下代码。当没有提供值时,我想将值从“price”复制到“newprice”。

import pandas as pd
articles = {"number": ["111", "222", "333"],
          "price": [12.46, 33.66, 43.35],
          "name": ["Article1", "Article2", "Article3"],
          "newprice": [11.24, None, None]}
df = pd.DataFrame(articles)
print(df)

# Select empty entries
mask = df['newprice'].isnull()
Run Code Online (Sandbox Code Playgroud)
# Version 1 (not working)
df.loc[mask, ['newprice']] = df.loc[mask, ['price']]
print(df)

# Output
#  number  price      name  newprice
# 0    111  12.46  Article1     11.24
# 1    222  33.66  Article2       NaN
# 2    333  43.35  Article3       NaN
Run Code Online (Sandbox Code Playgroud)
# Version 2 (working)
df.loc[mask, ['newprice']] = df['price']
print(df)

# …
Run Code Online (Sandbox Code Playgroud)

python dataframe pandas

5
推荐指数
1
解决办法
5710
查看次数

标签 统计

dataframe ×1

pandas ×1

python ×1