【问题标题】:How to update the column values and it's corresponding index based on a values of the column?如何根据列的值更新列值及其对应的索引?
【发布时间】:2017-03-27 23:27:05
【问题描述】:

在以下结构的pandas Dataframe中:

mcve_data =

alfa   alfa_id     beta    beta_id
a,c    7           c,de    8
c,d    7           d,f     9
l,mnk  8           c,d     9
j,k    8           d,e     9
tk,l   8           n,k     11
  • 我想在每一行中运行一个 for 循环,读取来自 key(alfa 和 beta)和 key_index(alfa_index、beta_index)的值。
  • 如果key 中的值的长度超过3,或者任何值的长度超过1 个字符。我希望 key-valueskey-index 都转换为句点 .

最终预期输出

alfa   alfa_id     beta    beta_id
a,c    7           .      .
c,d    7           d,f     9
.      .           c,d     9
j,k    8           d,e     9
.      .           n,k     11

我想写一个类似的函数(但它没有正常工作):

def check_and_convert(mcve_data):
    labels = (l, l + id) for l in mcve_data.columns.values

    def convert(lines):
        for l,id in labels:
            if len(l) > 3:
                l = '.'
                id = '.'
        return l, id

        write this back to the file.

任何建议,

【问题讨论】:

    标签: python pandas if-statement for-loop dataframe


    【解决方案1】:

    您还可以通过使用str 访问器来一次检查列中每个值的长度,从而跳过内部 for 循环:

    keys = [k for k in df.columns if not k.endswith('_id')]
    for k in keys:
        df.loc[df[k].str.len()>3,[k,k+'_id']] = '.'
    

    【讨论】:

      【解决方案2】:

      您可以使用 for 循环和 iterrows()。见下文。

      import pandas as pd
      from StringIO import StringIO
      
      s = """alfa   alfa_id     beta    beta_id
      a,c    7           c,de    8
      c,d    7           d,f     9
      l,mnk  8           c,d     9
      j,k    8           d,e     9
      tk,l   8          n,k     11
      """
      
      df = pd.read_table(StringIO(s), delim_whitespace = True,  dtype ={'alfa': str, 'alfa_id': str,
                                                                       'beta': str, 'beta_id': str})
      
      # I create a lsit of keys and key index based on '_id' distinction
      
      keys = [i for i in df.columns if 'id' not in i]
      key_ids = [i+'_id' for i in keys]
      
      for index, row in df.iterrows():
          for k,kid in zip(keys, key_ids):
              if (len(row[k].split(','))>3 or any([len(i) > 1 for i in row[k].split(',')])):
                  df.set_value(index, kid, '.')
                  df.set_value(index, k, '.')
      
      
      print df
      

      结果

        alfa alfa_id beta beta_id
      0  a,c       7    .       .
      1  c,d       7  d,f       9
      2    .       .  c,d       9
      3  j,k       8  d,e       9
      4    .       .  n,k      11
      

      【讨论】:

      • 非常感谢您的回答。但是,我想申请 for-loop,原因是 - 有很多(大约 100 个)keys and key_id,而不仅仅是 2 个。
      • 我用第二个 for 循环编辑了代码。对于所有的键和 key_ids
      • 感谢您的更新。那些int 值被转换为strings 的原因是什么,比如'11'。我会尽力为它找到解决方案,但如果你能毫不费力地做到这一点,我将不胜感激。
      • pandas read_table 以 int 形式读取数据,因此我将文本数据更改为字符串。但现在应该没问题了。
      猜你喜欢
      • 2020-02-19
      • 2022-08-09
      • 2021-10-19
      • 2022-08-18
      • 2023-03-05
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多