【问题标题】:Python - Iterate through multiple dataframes and append data to a new dataframePython - 遍历多个数据帧并将数据附加到新数据帧
【发布时间】:2022-01-10 14:28:33
【问题描述】:

我有 3 个熊猫数据框。我想将每次迭代中的每一行附加到现有数据帧。

示例如下:

DF1 =

col1 col2 col3
a     a    a
d     d    d
g     g    g

DF2=

col1 col2 col3
b     b    b
e     e    e
h     h    h

DF3=

col1 col2 col3
c     b    b
f     f    f
i     i    i

clean_DF =

col1 col2 col3
a     a    a
b     b    b 
c     c    c
d     d    d
e     e    e
f     f    f
g     g    g
h     h    h 
i     i    i

虚拟代码:

for i,j in df1.itterows():
   for a,b in df2.itterows():
       for c,d in df2.itterrows():
clean_df.append(i,j,a,b,c,d)

请有人指出我正确的方向吗?

【问题讨论】:

    标签: python pandas for-loop


    【解决方案1】:

    连接它们,使用keys 参数将索引与每个原始数据帧中的行关联,然后交换索引级别并按此索引对数据帧进行排序。

    df1 = pd.DataFrame([["a", "a", "a"], ["d", "d", "d"], ["g", "g", "g"]], columns=["col1", "col2", "col3"])
    df2 = pd.DataFrame([["b", "b", "b"], ["e", "e", "e"], ["h", "h", "h"]], columns=["col1", "col2", "col3"])
    df3 = pd.DataFrame([["c", "c", "c"], ["f", "f", "f"], ["i", "i", "i"]], columns=["col1", "col2", "col3"])
    clean_df = pd.concat([df1, df2, df3], keys=range(3)).swaplevel().sort_index()
    

    这假设每个数据帧当前都有一个索引并按该索引排序。如果您有可能未按索引排序的数据框,并且您想保留它们当前的排序顺序,那么您可以在连接它们之前重置它们的索引。

    dfs = [df.reset_index() for df in [df1, df2, df3]]
    clean_df = pd.concat(dfs, keys=range(len(dfs))).swaplevel().sort_index()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 2018-11-13
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多