Python pandas 将单元格值移动到同一行中的另一个单元格

Python pandas move cell value to another cell in same row

我有一个这样的数据框:

id   Description     Price     Unit
1    Test Only       1254       12
2    Data test       Fresher    4
3    Sample          3569       1
4    Sample Onces    Code test 
5    Sample          245        2

我想从 Price 列移到左边的 Description 列,如果不是整数则变为 NaN。我没有要调用或匹配的特定词,唯一的问题是如果 Price 列具有非整数值,则该字符串值移至 Description 列。

我已经尝试了 pandas replaceconcat 但它不起作用。

期望的输出是这样的:

id   Description     Price     Unit
1    Test Only       1254       12
2    Fresher                    4
3    Sample          3569       1
4    Code test     
5    Sample          245        2

使用:

#convert valeus to numeric
price = pd.to_numeric(df['Price'], errors='coerce')
#test missing values
m = price.isna()

#shifted only matched rows
df.loc[m, ['Description','Price']] = df.loc[m, ['Description','Price']].shift(-1, axis=1)
print (df)
   id Description Price
0   1   Test Only  1254
1   2     Fresher   NaN
2   3      Sample  3569
3   4   Code test   NaN
4   5      Sample   245

如果在输出 Price 列中需要数值:

df = df.assign(Price=price)
print (df)
   id Description   Price
0   1   Test Only  1254.0
1   2     Fresher     NaN
2   3      Sample  3569.0
3   4   Code test     NaN
4   5      Sample   245.0

这应该有效

# data
df = pd.DataFrame({'id': [1, 2, 3, 4, 5],
                   'Description': ['Test Only', 'Data test', 'Sample', 'Sample Onces', 'Sample'],
                   'Price': ['1254', 'Fresher', '3569', 'Code test', '245'],
                   'Unit': [12, 4, 1, np.nan, 2]})
# convert price column to numeric and coerce errors
price = pd.to_numeric(df.Price, errors='coerce')
# for rows where price is not numeric, replace description with these values
df.Description = df.Description.mask(price.isna(), df.Price)
# assign numeric price to price column
df.Price = price
df