我想將 pandas 資料幀中每一行中的值 0 替換為來自與資料幀的行索引具有相同索引的串列的值。
# here is my dataframe
df = pd.DataFrame({'a': [12, 52, 0], 'b': [33, 0, 110], 'c':[0, 15, 134]})
#here is the list
maxValueInRow = [3,5,34]
# the desired output would be:
df_updated = pd.DataFrame({'a': [12, 52, 3], 'b': [33, 5, 110], 'c':[34, 15, 134]})
我以為可能是這樣的
df.apply(lambda row: maxValueInRow[row.name] if row==0 else row, axis=1)
但這沒有用,并產生了“系列的真值是模棱兩可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。錯誤。任何想法將不勝感激。
uj5u.com熱心網友回復:
這是您需要的:
# here is my dataframe
df = pd.DataFrame({'a': [12, 52, 0], 'b': [33, 0, 110], 'c':[0, 15, 134]})
#here is the list
maxValueInRow = [3,5,34]
for index, row in df.iterrows():
for column in df.columns:
if row[column] == 0:
df.iloc[index][column] = maxValueInRow[index]
df
輸出
| 一種 | b | C | |
|---|---|---|---|
| 0 | 12 | 33 | 3 |
| 1 | 52 | 5 | 15 |
| 2 | 34 | 110 | 134 |
更新
根據您的評論,似乎通過用相同的索引替換值,您的意思是別的。無論如何,這里是您的問題的更新:
# here is my dataframe
df = pd.DataFrame({'a': [12, 52, 0], 'b': [33, 0, 110], 'c':[0, 15, 134]})
data = df.to_dict()
maxValueInRow = [3,5,34]
i = 0
for chr, innerList in data.items():
for index in range(len(innerList)):
value = innerList[index]
if value == 0:
data[chr][index] = maxValueInRow[i]
i = 1
df = pd.DataFrame(data)
df
輸出
| 一種 | b | C | |
|---|---|---|---|
| 0 | 12 | 33 | 34 |
| 1 | 52 | 5 | 15 |
| 2 | 3 | 110 | 134 |
uj5u.com熱心網友回復:
你可以使用.replace:
df = pd.DataFrame({'a': [12, 52, 0], 'b': [33, 0, 110], 'c':[0, 15, 134]})
maxValueInRow = [3,5,34]
repl = {col: {0: value} for col, value in zip(df.columns, maxValueInRow)}
df_updated = df.replace(repl)
結果:
a b c
0 12 33 34
1 52 5 15
2 3 110 134
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/428734.html
上一篇:在不使用replace()函式的情況下替換一列中的值
下一篇:對缺失值使用插值時的問題
