简体   繁体   English

通过用列表替换单元格值来扩展pandas数据帧

[英]Expand pandas dataframe by replacing cell value with a list

I have a pandas dataframe like this below: 我有一个像下面这样的熊猫数据框:

A B C
a b c
d e f

where AB and C are column names. 其中AB和C是列名。 Now i have a list: 现在我有一个清单:

mylist = [1,2,3]

I want to replace the c in column C with list such as dataframe expands for all value of list, like below: 我想用列表中的c替换列C中的c,例如dataframe展开列表的所有值,如下所示:

A B C
a b 1
a b 2
a b 3
d e f

Any help would be appreciated! 任何帮助,将不胜感激!

I tried this, 我试过这个,

mylist = [1,2,3]
x=pd.DataFrame({'mylist':mylist})
x['C']='c'
res= pd.merge(df,x,on=['C'],how='left')
res['mylist']=res['mylist'].fillna(res['C'])

For further, 为了更进一步的,

del res['C']
res.rename(columns={"mylist":"C"},inplace=True)
print res

Output: 输出:

   A  B  C
0  a  b  1
1  a  b  2
2  a  b  3
3  d  e  f

You can use: 您可以使用:

print (df)
   A  B  C
0  a  b  c
1  d  e  f
2  a  b  c
3  t  e  w
mylist = [1,2,3]

idx1 = df.index[df.C == 'c']
df = df.loc[idx1.repeat(len(mylist))].assign(C=mylist * len(idx1)).append(df[df.C != 'c'])
print (df)
   A  B  C
0  a  b  1
0  a  b  2
0  a  b  3
2  a  b  1
2  a  b  2
2  a  b  3
1  d  e  f
3  t  e  w

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM