繁体   English   中英

Pandas 添加行到 dataframe

[英]Pandas adding rows to dataframe

我正在尝试向我的数据框添加更多行或记录,假设它看起来像这样:

ID   age   
44   23
31   25 

我有一个 CSV 文件存储在另一个没有标题的数据框中

33   55
22   23
29   22

现在我想要一个看起来像这样的新数据框

ID   age   
44   23
31   25 
33   55
22   23
29   22

我试过使用 append 和 concat 但我没有得到我想要的结果

假设df1 / df2 ,可以使用set_axis复制第一个 DataFrame 的轴,然后concat

out = pd.concat([df1, df2.set_axis(df1.columns, axis=1)], ignore_index=True)

output:

   ID  age
0  44   23
1  31   25
2  33   55
3  22   23
4  29   22

注意。 ignore_index=True是可选的,这只是为了避免重复索引。 没有它:

   ID  age
0  44   23
1  31   25
0  33   55
1  22   23
2  29   22

Dataframe 具有轴(索引)--行索引(轴=0)--列索引(轴=1)。 Pandas 提供各种便利,可轻松组合系列 DataFrame。

pd.concat(objs, axis=0, join='outer', join_axes=None,ignore_index=False) 

      

• objs - 这是 Series、DataFrame 或 Panel 对象的序列或映射。

• axis - {0, 1, ...},默认为 0。这是要连接的轴。

• join - {'inner', 'outer'},默认为'outer'。 如何处理其他轴上的索引。 外部用于联合,内部用于交叉。

• ignore_index - boolean,默认为 False。 如果为 True,则不要使用连接轴上的索引值。 结果轴将标记为 0, ..., n - 1。

• join_axes - 这是索引对象的列表。 用于其他 (n-1) 轴的特定索引,而不是执行内部/外部集逻辑。

con = pd.concat([df1, df2]) # If column names are the same.
con = pd.concat([df1, df2], axis="columns") 

如果数据集之间的索引相同。 如果它们不同,默认情况下还会添加额外的索引(行),并填充 NaN 值。

两个 DataFrame 可能包含有关同一实体的不同类型的信息,并通过一些共同的特征/列链接。 为了加入这些 DataFrame,pandas 提供了多种函数,如 merge()、join() 等。
如果您有 SQL 背景,那么您可以使用 JOIN 语法中的合并操作名称。 您可以使用完全外连接、内连接、右连接、左连接、索引连接。

import pandas as pd

# Your first df will be ‘df’

df_2 = pd.dataframe({“Id”: [33, 22, 29], “Age”: [55, 23, 22]})

df = df.append(df_2, ignore_index=True)

您可以使用它,如果需要,可以使用 ignore_index。

output = pd.concat([df1, df2.set_axis(df1['columns'], axis=1)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM