How to append a list to pandas column, series?

£可爱£侵袭症+ 提交于 2020-06-14 06:35:28

问题


Asume that I have the following dataframe:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

I would like to extend col1 with array xtra. However this errors out.

xtra = [3,4]
df['col1'].append(xtra)

How can I append xtra to df.col1, so that the final otuput would looks as so?

   col1  col2
0     1     3
1     2     4
2     3     nan
3     4     nan

回答1:


just copy the same format you used (dict) to make a dataframe like so:

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

xtra = {'col1': [3,4]}

df = df.append(pd.DataFrame(xtra))



回答2:


Use pd.DataFrame and DataFrame.append:

df = df.append(pd.DataFrame(xtra, columns=['col1']), ignore_index=True)

print(df)
  col1  col2
0     1   3.0
1     2   4.0
2     3   NaN
3     4   NaN



回答3:


You can also add those rows without creating annother Dataframe by iterating on xtra:

for val in xtra:
    df = df.append({'col1' : val}, ignore_index=True)


来源:https://stackoverflow.com/questions/56127227/how-to-append-a-list-to-pandas-column-series

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!