簡體   English   中英

將相同的列表添加到新列中的pandas DataFrame中的每一行

[英]Adding the same list to each row in a pandas DataFrame in a new column

在pandas DataFrame中, foo例如:

>>> foo
   col1  col2
0     1     0
1     2     0
2     3     1

如果要添加新列,則可以使用相同的值

>>> foo['col3'] = 1
>>> foo
   col1  col2  col3
0     1     0     1
1     2     0     1
2     3     1     1

如果要添加另一個新列,則可以使用特定值

>>> foo['col4'] = ['a', 'b', 'c']
>>> foo
   col1  col2  col3  col4
0     1     0     1     a
1     2     0     1     b
2     3     1     1     c

但我想要做的是將相同的列表添加到每一行作為新列。 就像是

>>> myList = [True, False, False, True]
>>> foo['col5'] = {...something something something...}
>>> foo
   col1  col2  col3  col4                        col5
0     1     0     1     a  [True, False, False, True]
1     2     0     1     b  [True, False, False, True]
2     3     1     1     c  [True, False, False, True]

使用前面的方法會導致ValueError('Length of values does not match length of ' 'index') 所以此刻,我的{...something something something...}行是foo['col5'] = [myList] * foo.shape[0] 但我想知道,有更好的方法嗎?

使用列表理解。

v = [True, False, False, True]
df['col5'] = [v for _ in range(len(df))]

df
   col1  col2                        col5
0     1     0  [True, False, False, True]
1     2     0  [True, False, False, True]
2     3     1  [True, False, False, True]

你可能很想使用它

df['col5'] = [True, False, False, True] * len(df)

但是,每條記錄實際上都引用了相同的列表。 嘗試這個 -

df.loc[0, 'col5'][0] = False
df

   col1  col2                         col5
0     1     0  [False, False, False, True]
1     2     0  [False, False, False, True]
2     3     1  [False, False, False, True]

您會看到更改會反映在所有子列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM