简体   繁体   English

Python:如何执行以下数据帧操作

[英]Python : How do I perform the below Dataframe Operation

I have two dataframes我有两个数据框

在此处输入图片说明 在此处输入图片说明

codes are below for the two dfs下面是两个 dfs 的代码

import pandas as pd
df1 = pd.DataFrame({'income1': [-13036.0, 1200.0, -12077.5, 1100.0],
                   'income2': [-30360.0, 2000.0, -2277.5, 1500.0],

})


df2 = pd.DataFrame({'name1': ['abc', 'deb', 'hghg', 'gfgf'],
                   'name2': ['dfd', 'dfd1', 'df3df', 'fggfg'],

})

I want to combine the 2 dfs to get a single df with names against the respective income values, as shown below.我想将这 2 个 dfs 组合起来,以得到一个名称与相应收入值相对应的 df,如下所示。 Any help is appreciated.任何帮助表示赞赏。 Please note that I want it in the same sequence as shown in my output.请注意,我希望它与我的输出中显示的顺序相同。

在此处输入图片说明

Here is possible convert values to numpy array and flatten with pass to DataFrame cosntructor:以下是可能的将值转换为 numpy 数组并通过传递给DataFrame函数进行展平:

df = pd.DataFrame({'Name': np.ravel(df2.to_numpy()), 
                   'Income': np.ravel(df1.to_numpy())})
print (df)

    Name   Income
0    abc -13036.0
1    dfd -30360.0
2    deb   1200.0
3   dfd1   2000.0
4   hghg -12077.5
5  df3df  -2277.5
6   gfgf   1100.0
7  fggfg   1500.0

Or concat with DataFrame.stack and Series.reset_index for default index values:concatDataFrame.stackSeries.reset_index默认的索引值:

df = pd.concat([df2.stack().reset_index(drop=True), 
                df1.stack().reset_index(drop=True)],axis=1, keys=['Name','Income'])
print (df)
    Name   Income
0    abc -13036.0
1    dfd -30360.0
2    deb   1200.0
3   dfd1   2000.0
4   hghg -12077.5
5  df3df  -2277.5
6   gfgf   1100.0
7  fggfg   1500.0

Try this:尝试这个:

incomes = pd.concat([df1.income1, df1.income2], axis = 0)
names   = pd.concat([df2.name1  , df2.name2]  , axis = 0)

df = pd.DataFrame({'Name': names, 'Incomes': incomes})

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

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