【问题标题】:Rename variables of one dataframe by joining the values of another dataframe by using a Loop in Python通过在 Python 中使用循环连接另一个数据帧的值来重命名一个数据帧的变量
【发布时间】:2021-07-20 01:46:15
【问题描述】:

我有两个数据框。 第一个数据框有方向

df1

   Direction 
0  sb
1  nb
2  wb
3  eb

第二个df2是

   LT Thr RT UT LT.1 Thr.1 RT.1 UT.1 LT.2 Thr.2 RT.2 UT.2
0  
1
2
3

我希望能够遍历 df2 的名称并通过使用方向 df 连接来重命名它们,如下所示:

df2

   sb_LT sb_Thr sb_RT sb_UT nb_LT nb_Thr nb_RT nb_UT wb_LT wb_Thr wb_RT wb_UT
0  
1
2
3

这可能吗?

【问题讨论】:

  • 第一个索引处的sb 和第0 个索引处的nb。所以这是一个错误吗?
  • 很抱歉。我已经更新它以保持一致。
  • @joshuah9 df1中的directionsdf2中的列名有什么关系?
  • @ShubhamSharma 两张表之间的关系是 df2 具有交叉口每条路段的交通、LT、Thr、RT、UT 等的移动,这就是它们重复的原因。 df1 有方法的方向。
  • @joshuah9 df1的索引和df2中列名后缀的numbers之间是否有顺序关系

标签: python pandas loops concatenation


【解决方案1】:

你可以试试

new_columns = [df1.iloc[1,0]+"_"+x.split(".")[0] if '1' in x else 
               df1.iloc[2,0]+"_"+x.split(".")[0] if '2' in x else 
               df1.iloc[3,0]+"_"+x.split(".")[0] if '3' in x else 
               df1.iloc[0,0]+"_"+x.split(".")[0] for x in df2]

df2.columns = new_columns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2020-12-18
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多