如何使用包含字符串值的列表填充Pandas数据框列

3

我有一个有142行的数据帧。 我创建了一个新列。 我想用包含字符串的列表来填充这个新列。

my_list = ['abc','def','hig']
df['names'] = df['names'].fill(my_list) #pseudo code

我想用列表中相同的顺序填充“名称”列中的142行字符串值。

The output should be as:   

     names
   1 abc
   2 def
   3 hig
   4 abc
   5 def

你想用这个列表填满所有的142行吗?那么 df['names']=[['abc','def','hig']]*len(df) 就可以了吗? - anky
我认为是这样的 @anky_91 - Kumpelinus
我也考虑过这个问题@anky_91,但我认为一定有更好的解决方案。 - Kumpelinus
@EduardoSousa 那不会适合所有的142行,对吧? - anky
1
顺便提一下,尽量避免使用保留变量名,不要使用 list,而是使用类似 my_list 的名称。 - Erfan
显示剩余2条评论
3个回答

7

我认为你需要类似下面这样使用 np.resize 来根据数据框的大小调整列表的大小。

数据框示例:

df = pd.DataFrame(np.random.randint(0,100,size=(5,4)),columns=list('ABCD'))

    A   B   C   D
0  10  99   0  61
1  55   0  52  53
2  34  88  79  54
3  25  32   1  89
4  39  30  77   5

解决方案:

mylist=['abc','def','hig']
df['names'] = np.resize(mylist,len(df))
print(df)

    A   B   C   D names
0  10  99   0  61   abc
1  55   0  52  53   def
2  34  88  79  54   hig
3  25  32   1  89   abc
4  39  30  77   5   def

3
你差不多就快成功了。试试这个:
import pandas as pd
list = ['abc','def','hig']
df=pd.DataFrame(list)
df.columns=['names'] #provides a name for the column

df_repeated = pd.concat([df]*48, ignore_index=True)

这会给你 48*3=144 行。然后,

df_repeated =df_repeated.reindex(df_repeated.index.drop(144)).reset_index(drop=True)

1
啊啊啊。好的,让我想一想。 - merit_2

2

只需将列表分配给列,像这样; 它将同时创建名为“names”的列并将其填充到列表中:

df['names'] = my_list

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