【问题标题】:Add Uneven Sized Data Columns in Pandas在 Pandas 中添加大小不一的数据列
【发布时间】:2019-07-11 03:58:17
【问题描述】:

我想将列表作为列添加到 df 数据框。列表的大小与列的长度不同。

df = 
A   B   C
1   2   3
5   6   9
4   
6       6
8       4
2       3
4   
6       6
8       4


D = [11,17,18]

我想要以下输出

df = 
A   B   C   D
1   2   3   11
5   6   9   17
4           18
6       6
8       4
2       3
4   
6       6
8       4

我正在执行以下操作,通过添加“nan”将列表扩展到数据框的大小

# number of nan value require for the list to match the size of the column
extend_length = df.shape[0]-len(D)

# extend the list 
D.extend(extend_length * ['nan'])

# add to the dataframe
df["D"] = D

A   B   C   D
1   2   3   11
5   6   9   17
4           18
6       6   nan
8       4   nan
2       3   nan
4           nan
6       6   nan
8       4   nan

其中“nan”被视为字符串,但我希望它为空而不是“nan”,因此,如果我在 D 列中搜索有效单元格的数量,它将提供 3 的输出。

【问题讨论】:

标签: python pandas


【解决方案1】:

将列表添加为Series 将直接处理此问题。

D = [11,17,18]
df.loc[:, 'D'] = pd.Series(D)

【讨论】:

    【解决方案2】:

    df 上的简单pd.concat 和一系列D 如下:

    pd.concat([df, pd.Series(D, name='D')], axis=1)
    

    或

    df.assign(D=pd.Series(D))
    
    Out[654]:
       A    B    C     D
    0  1  2.0  3.0  11.0
    1  5  6.0  9.0  17.0
    2  4  NaN  NaN  18.0
    3  6  NaN  6.0   NaN
    4  8  NaN  4.0   NaN
    5  2  NaN  3.0   NaN
    6  4  NaN  NaN   NaN
    7  6  NaN  6.0   NaN
    8  8  NaN  4.0   NaN
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 2016-03-28
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多