【问题标题】:Filling cell values horizontally in Pandas dataframe在 Pandas 数据框中水平填充单元格值
【发布时间】:2017-08-13 15:49:00
【问题描述】:

我知道 bfill 和 ffill 在同一列的行中填充值。但是,当您需要在数据框中的某些多列中填充值时,您该怎么做呢?

示例如下:

初始df:

import pandas as pd
inidf = [('Prod', ['P1', 'P2']),
 ('A', ['1', '1']),
 ('1', ['', '40']),
 ('2', ['10', '60']),
 ('3', ['30', '']),
 ('B', ['1', '2']),             
 ]
df = pd.DataFrame.from_items(inidf)
df

  Prod  A   1   2   3  B
0   P1  1      10  30  1
1   P2  1  40  60      2

目标df:

tgtdf = [('Prod', ['P1', 'P2']),
 ('A', ['1', '1']),
 ('1', ['10', '40']),
 ('2', ['10', '60']),
 ('3', ['30', '60']),
 ('B', ['1', '2']),             
 ]
df2 = pd.DataFrame.from_items(tgtdf)
df2

  Prod  A   1   2   3  B
0   P1  1  10  10  30  1
1   P2  1  40  60  60  2

在我上面的示例中,要定位的列是名为 1、2 和 3 的列。在第一行中,第一个目标列(名为 1)有一个缺失值,在这种情况下是从下一个填充的列复制而来(命名为 2)。在第二行中,最后一个目标列(名为 3)有一个缺失值,在本例中是从先前填充的列(名为 2)复制而来的。

【问题讨论】:

  • 是否需要查找 fillbfill 的行?如果2 列中没有值有时被bfill 替换,有时被ffill 替换,是否有可能?有多列?

标签: python pandas dataframe reshape linear-interpolation


【解决方案1】:

您可以先使用replace 将空格转换为NaNs。

然后为bfillffill 选择行替换为axis=1 以替换为行:

df = df.replace('', np.nan)
bfill_rows = [0] #if necessary specify more values of index
ffill_rows = [1] #if necessary specify more values of index

df.loc[bfill_rows] = df.loc[bfill_rows].bfill(axis=1)
df.loc[ffill_rows] = df.loc[ffill_rows].ffill(axis=1)
print (df)
  Prod  A   1   2   3  B
0   P1  1  10  10  30  1
1   P2  1  40  60  60  2

如有必要,还可以指定列:

df = df.replace('', np.nan)
cols = ['1','2','3']
bfill_rows = [0]
ffill_rows = [1]

df.loc[bfill_rows, cols] = df.loc[bfill_rows, cols].bfill(axis=1)
df.loc[ffill_rows, cols] = df.loc[ffill_rows, cols].ffill(axis=1)
print (df)

  Prod  A   1   2   3  B
0   P1  1  10  10  30  1
1   P2  1  40  60  60  2

【讨论】:

  • 嗯,很遗憾只能接受一个答案... :(
【解决方案2】:

NaNs 和第一个ffill 替换所有空格,然后在axis=1 上用bfill 替换列'1','2','3'

In [31]: df[['1','2','3']] = df[['1','2','3']].replace('', np.nan).ffill(1).bfill(1)

In [32]: df
Out[32]:
  Prod  A   1   2   3  B
0   P1  1  10  10  30  1
1   P2  1  40  60  60  2

【讨论】:

  • 效果很好。谢谢你,约翰
【解决方案3】:

首先,将空引号替换为 NaN 值。然后根据需要 ffill 或 bfill,指定axis=0。选择给定行时,轴为0,因为此类选择的结果是一个系列。如果您要选择多行(例如整个数据框),那么轴将是 1

df = df.replace('', np.nan)
df.iloc[0, :].bfill(axis=0, inplace=True)  # Backfill first row.
df.iloc[1, :].ffill(axis=0, inplace=True)  # Forwardfill second row.

>>> df
  Prod  A   1   2   3  B
0   P1  1  10  10  30  1
1   P2  1  40  60  60  2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多