我有这个数据帧:
索引 | id | <1-t><2-t>3-t | ||
---|---|---|---|---|
2022-01-06 | 0 | 5 | 4 | 2 |
2022-01-05 | 1 | 3 | 5 | |
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 |
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)
以下是使用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
假设您的数据如下所示:
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
即,您在上表中标记为Index的是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
。
编辑:我忘了在列中使用索引值。现在应该可以了。
这对我有效:
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"]