[英]Adding the same list to each row in a pandas DataFrame in a new column
In a pandas DataFrame, foo
for example: 在pandas DataFrame中,
foo
例如:
>>> foo
col1 col2
0 1 0
1 2 0
2 3 1
If you want to add a new column, all with the same value you can do 如果要添加新列,则可以使用相同的值
>>> foo['col3'] = 1
>>> foo
col1 col2 col3
0 1 0 1
1 2 0 1
2 3 1 1
If you want to add another new column, all with specific values you can do 如果要添加另一个新列,则可以使用特定值
>>> 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
But what I want to do is add the same list to each row as new column. 但我想要做的是将相同的列表添加到每一行作为新列。 Something like
就像是
>>> 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]
Using the previous method results in ValueError('Length of values does not match length of ' 'index')
. 使用前面的方法会导致
ValueError('Length of values does not match length of ' 'index')
。 So at the moment, my {...something something something...}
line is foo['col5'] = [myList] * foo.shape[0]
. 所以此刻,我的
{...something something something...}
行是foo['col5'] = [myList] * foo.shape[0]
。 But I'm wondering, is there a better way? 但我想知道,有更好的方法吗?
Use a list comprehension. 使用列表理解。
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]
You might be tempted to use 你可能很想使用它
df['col5'] = [True, False, False, True] * len(df)
However, each record actually references the same list. 但是,每条记录实际上都引用了相同的列表。 Try this -
尝试这个 -
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]
You'll see the change is reflected across all sublists. 您会看到更改会反映在所有子列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.