Python Pandas数据框架 - 将列表赋值给多个单元格

7

我有一个像这样的 DataFrame

name col1 col2
 a    aa   123
 a    bb   123
 b    aa   234

以及一个列表

[1, 2, 3]

我希望用列表替换每行 col1 = 'aa' 的 col2。
name col1     col2
 a    aa   [1, 2, 3]
 a    bb       123
 b    aa   [1, 2, 3]

我尝试了类似于以下的内容:

df.loc[df[col1] == 'aa', col2] = [1, 2, 3]

但是它给我报错:

ValueError: could not broadcast input array from shape (xx,) into shape (yy,)

我该如何解决这个问题?

5个回答

4

简单点,使用np.where就可以了。以下是代码示例:

df['col2']=np.where(df['col1']=='aa', str(lst), df['col2'])

可以使用双括号内锁定的列表来代替使用pd.Series

df['col2']=np.where(df['col1']=='aa', pd.Series([lst]), df['col2'])

2
除了这个方法不能用于列表。你在这里将其转换为字符串,这也适用于 OP 的方法。 - mozway
OP已经指定,尽管进行了编辑。Pd.Series在列表中锁定。可以通过插入后尝试"explode"来检查。 - wwnde

2
import pandas as pd
df = pd.DataFrame({"name":["a","a","b"],"col1":["aa","bb","aa"],"col2":[123,123,234]})
l = [1,2,3]
df["col2"] = df.apply(lambda x: l if x.col1 == "aa" else x.col2, axis =1)
df

0

使用if/else的列表推导应该可以工作

df['col2'] = [x['col2'] if x['col1'] != 'aa' else [1,2,3] for ind,x in df.iterrows()]

0

使用for循环做这件事是安全的。

df.col2 = df.col2.astype(object)
for x in df.index:
    if df.at[x,'col1'] == 'aa':
       df.at[x,'col2'] = [1,2,3]
       
df
  name col1       col2
0    a   aa  [1, 2, 3]
1    a   bb        123
2    b   aa  [1, 2, 3]

0

你也可以使用:

data = {'aa':[1,2,3]}
df['col2'] = np.where(df['col1'] == 'aa', df['col1'].map(data), df['col2'])

你应该小心使用这个,因为这样做会将列表更改为两个位置:

df['col2'].loc[0].append(5)
print(df)
#OUTPUT
  name col1          col2
0    a   aa  [1, 2, 3, 5]
1    a   bb           123
2    b   aa  [1, 2, 3, 5]

但这没问题:

df = df.loc[1:]
print(df)
#OUTPUT
  name col1       col2
1    a   bb        123
2    b   aa  [1, 2, 3]

我认为这与其他提出的解决方案不同,因为col2将包含对同一列表对象的多个引用。我不确定这是否是OP想要的。 - hilberts_drinking_problem
是的,你说得对,你必须小心使用它。 - Muhammad Hassan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接