【问题标题】:how to change the row of a DataFrame depending on values of one column如何根据一列的值更改 DataFrame 的行
【发布时间】:2022-07-04 22:49:14
【问题描述】:

我有一个包含多个时间序列的巨大数据框,如下面的链接所示。

Dataframe with multiple time series

最后应该有一个数据框,其值与以前相同,除非 g 列中没有值 (nan)。简而言之,如果 g 列中有一个值,则所有其他行都应该保持不变。如果 g 列中有“nan”,则该行中的所有其他值也应为“nan”。此数据框中最多有 200 列,因此是否可以在不写单个列名的情况下以某种方式编写它就像很多例子一样。我用 df.iloc 和 np.where 尝试过,但老实说,我无法定义使其工作的条件。

Solution with rows adapted

我希望有人可以帮助我。 提前致谢。

【问题讨论】:

  • 不要发布数据/代码的图片。在问题中发布实际数据示例和代码。

标签: python pandas dataframe time-series


【解决方案1】:
for index in df.index:
    if np.isnan(df.loc[index, "g"]):
        df.loc[index, :] = np.nan

如果我正确理解您的问题,这应该可以工作。

【讨论】:

    【解决方案2】:
    import pandas as pd
    import numpy as np
    
    columns = ['Date','a','b','c','d','e','f','g']
    data = [
      ['01.06.2022','0,574','0,2342','0,574','0,2342','0,574','0,2342','0,574'],
      ['02.06.2022','0,574','0,2342','0,574','0,2342','0,574','0,2342',np.nan],
      ]
    
    
    df = pd.DataFrame(data, columns=columns)
    
    rows_to_adapt = list(df.columns)[1:-1]
    check_row = ['g']
    
    
    for col in rows_to_adapt:
        df[col] = np.where(df['g'].isnull(), np.nan, df[col])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-07
      • 2012-10-15
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2015-04-20
      相关资源
      最近更新 更多