简体   繁体   English

如何将计算结果添加到数据框中的新列?

[英]How do I add the results from a calculation to a new column in a dataframe?

I have this dataframe: 我有这个数据框:

    Dt1     Dt2
0   8/21/19 8/31/19
1   8/21/19 8/31/19
2   8/21/19 8/31/19
3   8/30/19 8/31/19

Then I wrote this code: 然后我写了这段代码:

for ind in df.index:
    date_str1 = df['Dt1'][ind]
    date_str2 = df['Dt2'][ind]
    date_object1 = datetime.strptime(date_str1, " %m/%d/%y")
    date_object2 = datetime.strptime(date_str2, " %m/%d/%y")
    d = date_object2-date_object1
    diff = d.days
    print(diff)

My results were: 我的结果是:

10
10
10
1

This is what I expect of the results, and now what I want to do is for each row in the dataframe, I want to create a new column (date_diff) and add these results to each row so in the end I have something like this: 这就是我期望的结果,现在我要做的是针对数据帧中的每一行,我想创建一个新列(date_diff)并将这些结果添加到每一行中,所以最后我得到了类似的结果:

    Dt1     Dt2      Date_diff
0   8/21/19 8/31/19  10
1   8/21/19 8/31/19  10
2   8/21/19 8/31/19  10
3   8/30/19 8/31/19  1

You can simply do: 您可以简单地执行以下操作:

df['Dt1'] = pd.to_datetime(df['Dt1'])
df['Dt2'] = pd.to_datetime(df['Dt2'])

df['Date_diff'] = df['Dt2'].sub(df['Dt1']).dt.days

创建一个列(具有纯零,NaN或其他内容),然后将其写在循环的末尾,即df.iloc[ind,"Date_Diff"]=diff或具有一个列表Date_diff=[] ,然后附加在end Date_diff.append(diff) -最后将其写入到df df["Date_diff"]=Date_diff

暂无
暂无

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

相关问题 在 pandas dataframe 中,如何根据列值过滤行,进行计算并将结果分配给新列? - In a pandas dataframe, how can I filter the rows based on a column value, do calculation and assign the result to a new column? 如何向现有 dataframe 添加新列并用另一列的部分数据填充它? - How do I add a new column to an existing dataframe and fill it with partial data from another column? 如何将新列添加到 Spark DataFrame(使用 PySpark)? - How do I add a new column to a Spark DataFrame (using PySpark)? 如何将计算结果添加到带有字典的 dataframe 中? - how to add results of calculation into a dataframe with dictionary? 日期时间计算中的新 pandas DataFrame 列 - New pandas DataFrame column from datetime calculation 如何使用字符串(或其他某种元数据)中的逻辑将新列添加到(PySpark)Dataframe? - How do I add new a new column to a (PySpark) Dataframe using logic from a string (or some other kind of metadata)? 逐行计算pandas数据框中的新列 - Calculation new column in pandas dataframe from row by row calculation 如何将遍历列表的新结果附加到数据框中的新列中 - How may I append new results from iterating through a list, into a new column in the dataframe 如何将数据从一个 dataframe 添加到另一个 dataframe 上的新列 - how to add data from one dataframe to a new column on another dataframe 如何通过包含一列某些值的平均值的计算在 DataFrame 中创建新列 - How to create a new column in a DataFrame from a calculation that includes the mean of some values of one column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM