我有這個資料框:
| 指數 | ID | 1噸 | 2噸 | 3噸 |
|---|---|---|---|---|
| 2022-01-06 | 0 | 5 | 4 | 2 |
| 2022-01-05 | 1 | 3 | 5 | 4 |
| 2022-01-04 | 2 | 4 | 3 | 5 |
| 2022-01-03 | 3 | 3 | 0 | 1 |
| 2022-01-02 | 4 | 2 | 3 | 0 |
| 2022-01-01 | 5 | 1 | 2 | 4 |
“-t”列中的值是 id,我想用索引值替換這個值。我有 100 列要替換(n 列 -t),我嘗試將回圈 FOR 與 .loc 一起使用,但它不起作用。
有人幫助我嗎?
預期輸出:
| 指數 | ID | 1噸 | 2噸 | 3噸 |
|---|---|---|---|---|
| 2022-01-05 | 0 | 2022-01-01 | 2022-01-02 | 2022-01-04 |
| 2022-01-05 | 1 | 2022-01-03 | 2022-01-01 | 2022-01-02 |
| 2022-01-04 | 2 | 2022-01-02 | 2022-01-03 | 2022-01-01 |
| 2022-01-03 | 3 | 2022-01-03 | 2022-01-05 | 2022-01-05 |
| 2022-01-02 | 4 | 2022-01-04 | 2022-01-03 | 2022-01-05 |
| 2022-01-01 | 5 | 2022-01-05 | 2022-01-04 | 2022-01-02 |
uj5u.com熱心網友回復:
for nm in df.columns:
if nm.endswith("-t"):
tmp = df.Index[df.loc[:, nm]]
tmp.index = df.index
df.loc[:, nm] = tmp
df
# Index id 1-t 2-t 3-t
# 0 2022-01-06 0 2022-01-01 2022-01-02 2022-01-04
# 1 2022-01-05 1 2022-01-03 2022-01-01 2022-01-02
# 2 2022-01-04 2 2022-01-02 2022-01-03 2022-01-01
# 3 2022-01-03 3 2022-01-03 2022-01-06 2022-01-05
# 4 2022-01-02 4 2022-01-04 2022-01-03 2022-01-06
# 5 2022-01-01 5 2022-01-05 2022-01-04 2022-01-02
要么
def foo(i, s):
ans = i[s]
ans.index = i.index
return ans
df.apply(lambda x: foo(df.Index, x) if x.name.endswith("-t") else x)
uj5u.com熱心網友回復:
這是另一種使用方式replace():
d = dict(zip(df['id'],df['Index']))
df.replace({i:d for i in df.columns[df.columns.str.contains('-t')]})
輸出:
Index id 1-t 2-t 3-t
0 2022-01-06 0 2022-01-01 2022-01-02 2022-01-04
1 2022-01-05 1 2022-01-03 2022-01-01 2022-01-02
2 2022-01-04 2 2022-01-02 2022-01-03 2022-01-01
3 2022-01-03 3 2022-01-03 2022-01-06 2022-01-05
4 2022-01-02 4 2022-01-04 2022-01-03 2022-01-06
5 2022-01-01 5 2022-01-05 2022-01-04 2022-01-02
uj5u.com熱心網友回復:
假設您的資料如下所示:
id 1-t 2-t 3-t
Index
2022-01-06 0 5 4 2
2022-01-05 1 3 5 4
2022-01-04 2 4 3 5
2022-01-03 3 3 0 1
2022-01-02 4 2 3 0
2022-01-01 5 1 2 4
即您在上表中標記的索引是 Pandas 資料框的實際索引,您需要做的就是使用如下Dataframe.filter例程:
for col in data.filter(like='-t'):
data[col] = data.index[data[col]]
print(data)
# id 1-t 2-t 3-t
#Index
#2022-01-06 0 2022-01-01 2022-01-02 2022-01-04
#2022-01-05 1 2022-01-03 2022-01-01 2022-01-02
#2022-01-04 2 2022-01-02 2022-01-03 2022-01-01
#2022-01-03 3 2022-01-03 2022-01-06 2022-01-05
#2022-01-02 4 2022-01-04 2022-01-03 2022-01-06
#2022-01-01 5 2022-01-05 2022-01-04 2022-01-02
甚至可能有一種方法可以一次替換所有列。如果Index只是列的名稱,請替換data.index為data.Index.
編輯:我忘了使用列中的索引值。現在應該可以作業了。
uj5u.com熱心網友回復:
這對我有用:
for i in range(len(df)):
df.loc[i,"1-t"]=df.loc[df.loc[i,"1-t"],"Index"]
df.loc[i,"2-t"]=df.loc[df.loc[i,"2-t"],"Index"]
df.loc[i,"3-t"]=df.loc[df.loc[i,"3-t"],"Index"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451432.html
上一篇:根據另一個Dataframe上的條件替換Dataframe的列值
下一篇:拆分和堆疊多值列
