[英]What is the optimal way to create a new column in Pandas dataframe based on conditions from another row?
[英]Create new row in Pandas DataFrame based on conditions
我想遍历 dataframe 中的每一行,如果它符合某些条件,则创建另一行。 例如
A B C
Both 999 LP
London 1002 KI
Manchester 1005 BV
Both 1001 IG
将导致:
A B C
Both 999 LP
Both (Some calculation) LP
London 1002 KI
Manchester 1005 BV
Both 1001 IG
我们查看每一行,如果 A 列等于“Both”且 B 小于 1000,则插入一个新行,其中 col A 保持不变,col B 基于我编写的 function 和 col C 保持不变。
def create_new_row(row):
if row['A'] == "Both":
if row['B'] < 1000:
result = somefuction(row['B'])
return result
这是我到目前为止的代码,但我不知道如何获得我想要的 dataframe。
通过boolean indexing
过滤 dataframe 以获取满足您条件的行:
m = (df['A'] == "Both") & (df['B'] < 1000)
df1 = df[m].copy()
根据过滤后的数据库生成新行:
#sample function
def somefuction(x):
return x / 100
df1['B'] = df1['B'].apply(somefuction)
通过concat
将结果与原始 dataframe 连接, reset_index
DataFrame.sort_index 排序以获得正确的顺序,最后通过DataFrame.sort_index
创建默认索引:
df = pd.concat([df, df1]).sort_index(kind='mergesort').reset_index(drop=True)
print (df)
A B C
0 Both 999.00 LP
1 Both 9.99 LP
2 London 1002.00 KI
3 Manchester 1005.00 BV
4 Both 1001.00 IG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.