从python中的其他3个数据帧创建一个数据帧
我试图创建一个新的df,通过从3个(比如)其他数据帧中获取这些信息来总结我的关键信息从python中的其他3个数据帧创建一个数据帧,python,dataframe,Python,Dataframe,我试图创建一个新的df,通过从3个(比如)其他数据帧中获取这些信息来总结我的关键信息 dfdate = {'x1': [2, 4, 7, 5, 6], 'x2': [2, 2, 2, 6, 7], 'y1': [3, 1, 4, 5, 9]} dfdate = pd.DataFrame(df, index=range(0:4)) dfqty = {'x1': [1, 2, 6, 6, 8], 'x2': [3, 1, 1, 7, 5], 'y1': [2
dfdate = {'x1': [2, 4, 7, 5, 6],
'x2': [2, 2, 2, 6, 7],
'y1': [3, 1, 4, 5, 9]}
dfdate = pd.DataFrame(df, index=range(0:4))
dfqty = {'x1': [1, 2, 6, 6, 8],
'x2': [3, 1, 1, 7, 5],
'y1': [2, 4, 3, 2, 8]}
dfqty = pd.DataFrame(df2, range(0:4))
dfprices = {'x1': [0, 2, 2, 4, 4],
'x2': [2, 0, 0, 3, 4],
'y1': [1, 3, 2, 1, 3]}
dfprices = pd.DataFrame(df3, range(0:4))
假设以上3个数据帧是我的数据。比如,一些日期、数量和商品价格。我的新df将根据上述数据构建:
rng = len(dfprices.columns)*len(dfprices.index) # This is the len of new df
dfnew = pd.DataFrame(np.nan,index=range(0,rng),columns=['Letter', 'Number', 'date', 'qty', 'price])
现在,这就是我努力拼凑东西的地方。我试图获取dfdate中的所有数据,并将其放入新df中的一列中。与dfqty和dfprice相同。(因此3x5矩阵基本上转到1x15向量,并放入新的df中)
除此之外,我还需要dfnew中的两列作为标识符,它们来自旧df的列的名称
我试过循环,但没有用,也不知道如何将df转换成系列。但我期望的结果是:
dfnew:
'Lettercol','Numbercol', 'date', 'qty', 'price'
0 X 1 2 1 0
1 X 1 4 2 2
2 X 1 7 6 2
3 X 1 5 6 4
4 X 1 6 8 4
5 X 2 2 3 2
6 X 2 2 1 0
7 X 2 2 1 0
8 X 2 6 7 3
9 X 2 7 5 4
10 Y 1 3 2 1
11 Y 1 1 4 3
12 Y 1 4 3 2
13 Y 1 5 2 1
14 Y 1 9 8 3
其中数字0-14是索引。
字母=DFs中来自列标题的字母
编号=DFs中列标题的编号
接下来的3列是来自原始df的数据
(不要问为什么原始数据的格式如此有趣:)
非常感谢。我的上一个问题没有得到很好的接受,因此我尝试将这一个做得更好,谢谢使用:
#list of DataFrames
dfs = [dfdate, dfqty, dfprices]
#list comprehension with reshape
comb = [x.unstack() for x in dfs]
#join together
df = pd.concat(comb, axis=1, keys=['date', 'qty', 'price'])
#remove second level of MultiIndex and index to column
df = df.reset_index(level=1, drop=True).reset_index().rename(columns={'index':'col'})
#extract all values without first by indexing [1:] and first letter by [0]
df['Number'] = df['col'].str[1:]
df['Letter'] = df['col'].str[0]
cols = ['Letter', 'Number', 'date', 'qty', 'price']
#change order of columns
df = df.reindex(columns=cols)
print (df)
Letter Number date qty price
0 x 1 2 1 0
1 x 1 4 2 2
2 x 1 7 6 2
3 x 1 5 6 4
4 x 1 6 8 4
5 x 2 2 3 2
6 x 2 2 1 0
7 x 2 2 1 0
8 x 2 6 7 3
9 x 2 7 5 4
10 y 1 3 2 1
11 y 1 1 4 3
12 y 1 4 3 2
13 y 1 5 2 1
14 y 1 9 8 3
非常感谢。如果我们有一行额外的代码:df['identifier']=df['col'],即x1、x2和y2的一个col,如果我有另一个具有事务成本的df,比如:tcostmatrix=pd.DataFrame(np.NaN,index=range(0,4),columns=['x1',x2',tcoy1'])iloc[:,0]=0.2#tcost-x1 tradecostmatrix.iloc[:,1]=0.3#tcost x2 tradecostmatrix.iloc[:,2]=0.5#tcost x3(即x1=0.2,x2=0.3,y1=0.5)我如何用相应的tcost值创建一个新列?本质上我在python中寻找一个等价的vlookup?我想要的输出是tcost 0.2 1 0.2…14 0.5