我有三个数据框。我想从所有3个数据框中按日期2020-10-26
选择行,然后我要创建一个新的数据框。怎么做?
import pandas as pd
from datetime import date
date1 = date.fromisoformat('2020-10-25')
date2 = date.fromisoformat('2020-10-26')
date3 = date.fromisoformat('2020-10-27')
for x in range(3):
df = pd.DataFrame([(date1,f'Stu{x}j', x+1, f'Varan{x}j', x*400+2),
(date2,f'aja{x}k', x+2, f'Del{x}j', x*634+3),
(date3,f'Aadi{x}t', x+4, f'Mumb{x}j', x*454+4),
(date2,f'har{x}h', x+5, f'bom{x}j', x*124+5)],
columns =['Date','Name', 'Age',
'City', 'Salary'])
df.set_index('Date', inplace = True)
print(df)
答案 0 :(得分:1)
以下代码将为您提供帮助
import pandas as pd
from datetime import date
date1 = date.fromisoformat('2020-10-25')
date2 = date.fromisoformat('2020-10-26')
date3 = date.fromisoformat('2020-10-27')
res = pd.DataFrame()
for x in range(3):
df = pd.DataFrame([(date1,f'Stu{x}j', x+1, f'Varan{x}j', x*400+2),
(date2,f'aja{x}k', x+2, f'Del{x}j', x*634+3),
(date3,f'Aadi{x}t', x+4, f'Mumb{x}j', x*454+4),
(date2,f'har{x}h', x+5, f'bom{x}j', x*124+5)],
columns =['Date','Name', 'Age',
'City', 'Salary'])
temp = df[df['Date'].isin([date2])]
res = res.append(temp)
print(res)
旧方法:
fr = [df1, df2, df3]
full = pd.concat(fr).reset_index()
full[full.Date.isin([date2])]
答案 1 :(得分:0)
您可以这样做:
row1 = df1.loc[date2, :]
row2 = df2.loc[date2, :]
row3 = df3.loc[date2, :]
pd.concat([row1,row2,row3], axis=1).T
输出:
Name Age City Salary
2020-10-26 ajay 32 Delhi 25000
2020-10-26 Saumya 32 Kanpur 20000
2020-10-26 Aaditya 40 Dehradun 24000