【问题标题】:Add only all string values of pandas row as list in a new column仅将 pandas 行的所有字符串值添加为新列中的列表
【发布时间】:2020-01-06 19:35:56
【问题描述】:

我有一个熊猫数据框:

TKDM364             3424.32            3244.39            2724.48            1685.24             0            0
TKDM365             3744.64            3458.03            3132.46            2687.91             0            0
TKDM366             3523.18            4007.76            4487.74            2173.04             0            0
TKDM367             3471.77            3888.26            4032.71            4006.34             0            0
TKDM368   LF_Strut_Pressure  RF_Strut_Pressure  LR_Strut_Pressure  RR_Strut_Pressure             4            0
TKDM369   LF_Strut_Pressure  RF_Strut_Pressure  LR_Strut_Pressure  RR_Strut_Pressure             4            0
TKDM374             3361.51            3384.03            2023.38            2263.13             0            0
TKDM378   LF_Strut_Pressure  RF_Strut_Pressure  LR_Strut_Pressure  RR_Strut_Pressure             4            0
TKDM379             4294.54  RF_Strut_Pressure            4399.79            5525.08             1            1

我们在数据框中看到的奇怪字符串是列标题。这些字符串替换了 NaN 值

我想向数据框添加一个新列,如果last column == 1 中的行值,它将只为每一行添加列名(以字符串格式)。

预期输出:TKDM379 should show [RF_Strut_Pressure] 在新添加的列中。

也就是说,如果当前last column == 1中的值,则将这一行内的所有字符串值添加到一个列表中,并让这个列表成为新列和同一行中的值

PS:列名代替了 NaN 值(我是 python 新手,认为如果一行中出现一定数量的 NaN 值,这将是有条件地提取列名的好方法)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    以下是在每一行上使用.apply 的方法:

    import string
    lets = string.ascii_lowercase
    
    df['new_col'] = (df
                     .apply(lambda x: x[x.apply(lambda z: any([y for y in str(z) if y in lets]))] if x[6] == 1 else [], 
                     axis=1)
    
                      4  5  6              new_col  
    0            1685.24  0  0                   []  
    1            2687.91  0  0                   []  
    2            2173.04  0  0                   []  
    3            4006.34  0  0                   []  
    4  RR_Strut_Pressure  4  0                   []  
    5  RR_Strut_Pressure  4  0                   []  
    6            2263.13  0  0                   []  
    7  RR_Strut_Pressure  4  0                   []  
    8            5525.08  1  1  [RF_Strut_Pressure] 
    

    由于您没有提到 else 子句,我使用的是一个空列表。随意根据您的需要进行更改。

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 2012-12-09
      • 1970-01-01
      • 2020-10-18
      • 2021-11-30
      • 1970-01-01
      • 2019-11-23
      • 2021-03-09
      • 2019-01-14
      相关资源
      最近更新 更多