如何在Pandas中向新列添加字符串列表?

s4n0splo  于 2023-05-27  发布在  其他
关注(0)|答案(2)|浏览(176)

给定一个字符串数组a = ['foo',' bar','foo2'],你如何将它作为一个新列添加到现有的 Dataframe df中。

The shape of the df before adding:
  a b
0 3 3
1 3 3
2 3 3

after adding:
  a b new_column
0 3 3 foo
1 3 3 bar 
2 3 3 foo2
vltsax25

vltsax251#

把它分配进去。

>>> import pandas as pd
>>> df = pd.DataFrame({"a": [1,2,3], "b": [4,5,6]})
>>> df
   a  b
0  1  4
1  2  5
2  3  6
>>> df["c"] = ["foo", "bar", "foo2"]
>>> df
   a  b     c
0  1  4   foo
1  2  5   bar
2  3  6  foo2
>>>
djp7away

djp7away2#

如果你这样做,你就不必担心填充:

idx = 0
for thing in mylist:
    df.at[idx,'column_name'] = thing
    idx+=1

相关问题