【问题标题】:pandas how to add a column of one dataframe as a row into another dataframe熊猫如何将一个数据帧的一列作为一行添加到另一个数据帧中
【发布时间】:2018-12-13 12:48:54
【问题描述】:

我有以下df_1

 0      1        2        3
-1    201704   201705   201706
750     -1       -1       -1
760     12        0        0

我还有另外两个 DataFrame df_2

code    avg_days
750       12
760       9.6

df_3

year_month    avg_days
 201704        13.5
 201705        14.5
 201706        15.5

我喜欢先在df_1 中添加一行[0, 0, 0, 0, 0],然后用两个0s 填充df_2['avg_days'],使其看起来像[0, 0, 12, 9.6],然后将其插入到@987654333 的1 列中@,看起来像,

 0    1      2        3        4
-1    0   201704   201705   201706
 0    0      0        0        0
750   12    -1       -1       -1
760   9.6   12        0        0

最后,我想用两个0s 填充df_3['avg_days'],使其看起来像[0, 0, 13.5, 14.5, 15.5],然后将其插入为df_1 的第二行,看起来像,

 0    1      2        3        4
-1    0   201704   201705   201706
 0    0    13.5     14.5     15.5
750   12    -1       -1       -1
760   9.6   12        0        0

【问题讨论】:

  • 您的 code 列应该是您的索引,这将使您的生活 100% 更轻松。无论如何,最后一步都会乱七八糟

标签: python python-3.x pandas dataframe series


【解决方案1】:

您的数据缺乏结构:您想要的结果没有有意义的行和索引标签。因此,解决方案也很混乱:

# merge df1 with df3
mrg = df1.T.merge(df3.rename(columns={'year_month': 0}), how='outer')

# realign column order
mrg.columns = np.arange(mrg.shape[1])
mrg.insert(1, 3, mrg.pop(3))

# merge result with df2
res = mrg.T.merge(df2.rename(columns={'code': 0}), how='outer')

# realign column order and names
res.insert(1, 4, res.pop('avg_days'))
res = res.fillna(0)
res.columns = np.arange(res.shape[1])

print(res)

       0     1         2         3         4
0   -1.0   0.0  201704.0  201705.0  201706.0
1    0.0   0.0      13.5      14.5      15.5
2  750.0  12.0      -1.0      -1.0      -1.0
3  760.0   9.6      12.0       0.0       0.0

【讨论】:

  • +1 表示缺乏结构。许多人在处理数据时不了解索引(主键)的概念。
  • @ayorgo,是的,我想我们经常看到这种情况,人们从 Excel(或者,偶尔是 NumPy)迁移到 Pandas。无法替代阅读此处的文档。
  • 本来打算使用稍微不那么混乱的解决方案,但不知道该怎么做stackoverflow.com/questions/53742695/…
【解决方案2】:

我强烈建议您阅读 Pandas Dataframes 以及如何/为何使用 这些数据帧的索引和切片。您的问题(例如填充零) 建议您可能需要一些帮助来考虑在 数据框会做。如前所述,如果您保留它也会更有用 跟踪列和索引的含义。这是一个 替代解决方案:

# your data
df1 = pd.DataFrame({1:[201704.0,-1,12],2:[201705.0,-1,0],3:[201706.0,-1,0]}, 
index= [-1,750,760])
df2 = pd.DataFrame({'code': [750,760], 'avg_days':[12,9.6]})
df3 = pd.DataFrame({'year_month':[201704.0,201705.0,201706.0],'avg_days' 
[13.5,14.5,15.5]})

# add the rows
df1.loc[0] = np.zeros(df1.shape[1])

# set the indexes in your dataframe (I set name to None as I don't know what 
# you want)
df2.set_index('code', inplace=True)
df2.index.set_names([None], inplace=True)
df2.rename(columns={'avg_days': 0}, inplace=True)

# add the df2 data to df1
result = pd.concat([df1, df2], axis=1)

# again I am not sure what the columns mean in df1/result so I'll just use 
# apply here
month_to_avg_days_map = {k:v for k,v in df3.values}

def insert_value(col):
   month_year = col.loc[-1]
   if month_year in month_to_avg_days_map:
      return month_to_avg_days_map[month_year]
   return np.nan

result.loc[0,:] = result.apply(insert_value, axis=0)
result.fillna(0, inplace=True)

结果如你所愿。

【讨论】:

    猜你喜欢
    • 2013-11-18
    • 2021-05-08
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多