[英]Using values in a pandas dataframe as column names for another
This is my first dataframe.这是我的第一个 dataframe。
Date 0 1 2 3
2003-01-31 CA KY ID CO
2003-02-28 CA KY HI CO
2003-03-31 CA KY CO HI
This is my second dataframe.这是我的第二个 dataframe。
Date CA KY ID CO HI
2003-01-31 5 3 4 5 1
2003-02-28 2 7 8 4 5
2003-03-31 6 3 9 3 5
How do I get this dataframe to print as output?如何让这个 dataframe 打印为 output?
Date 0 1 2 3
2003-01-31 5 3 4 5
2003-02-28 2 7 5 4
2003-03-31 6 3 3 5
I am wondering if there is a way to use the whole dataframe as an index to another instead of having to loop through all the dates/columns.我想知道是否有一种方法可以使用整个 dataframe 作为另一个索引,而不必遍历所有日期/列。
You can use df.lookup
with df.apply
here.您可以在此处将
df.lookup
与df.apply
一起使用。
#
If `Date` is not index.
# df1.set_index('Date')
# 0 1 2 3
# Date
# 2003-01-31 CA KY ID CO
# 2003-02-28 CA KY HI CO
# 2003-03-31 CA KY CO HI
# df2.set_index('Date')
# CA KY ID CO HI
# Date
# 2003-01-31 5 3 4 5 1
# 2003-02-28 2 7 8 4 5
# 2003-03-31 6 3 9 3 5
def f(x):
return
df2.lookup(x.index, x)
df1.apply(f)
# df1.apply(lambda x:
df2.lookup(x.index, x)
0 1 2 3
Date
2003-01-31 5 3 4 5
2003-02-28 2 7 5 4
2003-03-31 6 3 3 5
This will print the values of dataframe df and the column name of dataframe df1.这将打印 dataframe df 的值和 dataframe df1 的列名。
print(df.rename(columns={i:j for i,j in zip(df.columns.tolist(),df1.columns.tolist())}))
if you want to make the changes permanent, add the parameter inplace=TRUE
如果要使更改永久化,请添加参数
inplace=TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.