我有一个有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行的数据帧。 我创建了一个新列。 我想用包含字符串的列表来填充这个新列。
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
我认为你需要类似下面这样使用 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
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)
只需将列表分配给列,像这样; 它将同时创建名为“names”的列并将其填充到列表中:
df['names'] = my_list
df['names']=[['abc','def','hig']]*len(df)
就可以了吗? - ankylist
,而是使用类似my_list
的名称。 - Erfan