拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 pythonpandasDataFrame-为多个单元格分配一个串列

pythonpandasDataFrame-为多个单元格分配一个串列

白鹭 - 2022-01-24 1960 0 0

我有一个像

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,)

我应该如何解决这个问题?

uj5u.com热心网友回复:

让它变得简单。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'])

uj5u.com热心网友回复:

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

uj5u.com热心网友回复:

带有 if/else 的串列理解应该可以作业

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

uj5u.com热心网友回复:

使用 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]

uj5u.com热心网友回复:

您还可以使用:

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]
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *