我有一個這樣的資料框:
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
如果不是整數,我想從價格列移到左側的描述列,然后變為 NaN。我沒有要呼叫或匹配的特定單詞,唯一的問題是如果價格列具有非整數值,則該字串值移動到描述列。
我已經嘗試過熊貓replace,concat但它不起作用。
期望的輸出是這樣的:
id Description Price Unit
1 Test Only 1254 12
2 Fresher 4
3 Sample 3569 1
4 Code test
5 Sample 245 2
uj5u.com熱心網友回復:
這應該作業
# 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

uj5u.com熱心網友回復:
利用:
#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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485528.html
標籤:python-3.x 熊猫 数据框
上一篇:分組并取平均字符長度
下一篇:如何將字典“附加”到嵌套字典中
