[英]Pandas: Add new column and assigning value from another dataframe by condition
[英]Pandas Dataframe - Add a new Column with value from another row
我正在尝试向我的 df 添加一个名为ordered_1day_ago
的新列。
DataFrame 目前看起来是这样的:
物品编号 | 订购日期 | 数量 |
---|---|---|
1个 | 12/2/21 | 3个 |
2个 | 12/3/21 | 2个 |
1个 | 12/3/21 | 2个 |
1个 | 12/4/21 | 3个 |
我希望它看起来像这样:
物品编号 | 订购日期 | 数量 | ordered_1day_ago |
---|---|---|---|
1个 | 12/2/21 | 3个 | 0 |
2个 | 12/3/21 | 2个 | 0 |
1个 | 12/3/21 | 2个 | 3个 |
1个 | 12/4/21 | 3个 | 2个 |
itemID
和ordered date
必须用于在下一个 orderedDate 插入数量,如果它在一天之内,如果不在一天之内,则ordered_1day_ago
为 0。
我们如何为此使用 pandas?
这是完整的解决方案:
import pandas as pd
# a dict to create th dataframe
d = {
'itemID':[1,2,1,1],
'orderedDate':['12/2/21', '12/3/21', '12/3/21', '12/4/21'],
'qty':[3,2,2,3]
}
# the old dataframe
df = pd.DataFrame(d)
print(df)
# some function to do what you want to based on rows
def some_function(row):
# code goes here
z = row['itemID'] + row['qty']
return z
# add the new column given the function above
df['ordered_1day_ago'] = df.apply(some_function, axis=1)
# the new datafdrame with the extra column
print(df)
这是原始的 df:
itemID orderedDate qty
0 1 12/2/21 3
1 2 12/3/21 2
2 1 12/3/21 2
3 1 12/4/21 3
这是添加了(示例)列的新 df:
itemID orderedDate qty ordered_1day_ago
0 1 12/2/21 3 4
1 2 12/3/21 2 4
2 1 12/3/21 2 3
3 1 12/4/21 3 4
您可以修改 function 以包含您希望的任何条件,以便新列ordered_1day_ago
包含您希望的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.