如何将列表附加到 pandas 列、系列?

2022-01-22 00:00:00 python pandas append

问题描述

假设我有以下数据框:

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

我想用数组 xtra 扩展 col1.但是这会出错.

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

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

如何将 xtra 附加到 df.col1,以使最终的 otuput 看起来像这样?

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


解决方案

只需复制您使用的相同格式 (dict) 即可制作如下数据框:

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))

相关文章