简体   繁体   English

从现有的 df (python - pandas) 创建新的 df

[英]Create new df from existing df (python - pandas)

I have created a data frame df1 like below,我创建了一个数据框 df1 如下所示,

data = {'ID':[1,2,3,4,5,6,7,8,9,10],
        'date_1':['2021-03-01','2021-03-02','2021-04-03','2021-03-04','2021-03-05','2021-03-06','2021-03-07','2021-03-08','2021-03-09','2021-03-10'],
        'date_2': ['2021-03-06','2021-03-07','2021-03-08','2021-03-09','2021-03-10','2021-03-11','2021-03-12','2021-03-13','2021-03-14','2021-03-15']
       }
df1 = pd.DataFrame(data, columns = ['ID','date_1','date_2'])
df1

This is the df1 output这是 df1 output 在此处输入图像描述

I am trying to create a new dataframe df2 with just one column 'date_3' from df1.我正在尝试创建一个新的 dataframe df2,其中只有来自 df1 的一列“date_3”。 The column 'date_3' in df2 ideally should be returning just the rows(dates) from df1 which meet the condition of the below statement (True),理想情况下,df2 中的“date_3”列应该只返回 df1 中满足以下语句条件的行(日期)(真),

df1['date_1'] <= df1['date_2']

Below is my approach but I am just getting the conditional output (True/False) and the not the actual date values,下面是我的方法,但我只是得到有条件的 output (True/False) 而不是实际的日期值,

data = [df1['date_1'] <= df1['date_2']]
headers = ['date_3']
df2 = pd.concat(data, axis=1, keys=headers)
df2

This is the output of df2这是df2的output 在此处输入图像描述

Use:利用:

In [489]: df2 = df[df['date_1'] <= df['date_2']]['date_1'].to_frame('date_3')

In [490]: df2
Out[490]: 
       date_3
0  2021-03-01
1  2021-03-02
3  2021-03-04
4  2021-03-05
5  2021-03-06
6  2021-03-07
7  2021-03-08
8  2021-03-09
9  2021-03-10

As advised by @ScottBoston, avoiding chain indexing:正如@ScottBoston 所建议的,避免链索引:

df2 = df.loc[df['date_1'] <= df['date_2'], 'date_1'].to_frame('date_3')

This:这个:

df2 = df.loc[df["date_1"]<= df["date_2"], ["ID", "date_1"]].copy()

df2.rename(columns= {"date_1": "date_3"})

will first subset based on your condition and only keep the ID and date_1 column, then you can rename the column将首先根据您的条件进行子集化,仅保留 ID 和 date_1 列,然后您可以重命名该列

It also makes it explicit that you get a copy and will prevent you from getting any setWithCopyWarnings if you make any modifications它还明确表明您会获得一份副本,并且如果您进行任何修改,它将阻止您获得任何 setWithCopyWarnings

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

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