【问题标题】:Insert rows in Python dataframe with conditions使用条件在 Python 数据框中插入行
【发布时间】:2022-12-10 14:53:19
【问题描述】:

我有一个大数据文件,如下所示。 我想在 D 列旁边添加两个新列(E 和 F),并将单元格 D3 和 D4 中的单元格 #(适用时)和城市/州数据分别移动到 E2 和 F2。挑战在于并非每个条目都有套房号。我需要先为那些没有套房号的条目插入一行,只为它们插入一行,而不是为那些已经有套房信息的条目插入一行。

我知道如何进行循环,但无法定义条件。一种方法是计算字符串的长度。我应该如何开始?非常感谢您的帮助!

【问题讨论】:

  • 输出将与下面显示的 Shane S 完全一样。

标签: python pandas dataframe insert conditional-statements


【解决方案1】:

这就是我会做的。我不建议在使用 pandas 时循环。有很多工具通常不需要。对此有些警告。你的电子表格有 NaN 我认为这实际上是 numpy np.nan 等价物。你也有空白我认为它是一个“”等价物。

import pandas as pd
import numpy as np

# dictionary of your data
companies = {
    'Comp ID': ['C1', '', np.nan, 'C2', '', np.nan, 'C3',np.nan],
    'Address': ['10 foo', 'Suite A','foo city', '11 spam','STE 100','spam town', '12 ham', 'Myhammy'],
    'phone': ['888-321-4567', '', np.nan, '888-321-4567', '', np.nan, '888-321-4567',np.nan],
    'Type': ['W_sale', '', np.nan, 'W_sale', '', np.nan, 'W_sale',np.nan],
}
# make the frames needed. 
df = pd.DataFrame( companies)
df1 = pd.DataFrame() # blank frame for suite and town columns

# Edit here to TEST the data types 
for r in range(0, 5):
    v = df['Comp ID'].values[r]
    print(f'this "{v}" is a ', type(v))

# So this will tell us the data types so we can construct our where(). Back to prior answer....

# Need a where clause it is similar to a if() statement in excel
df1['Suite'] = np.where( df['Comp ID']=='', df['Address'], np.nan)
df1['City/State'] = np.where( df['Comp ID'].isna(), df['Address'], np.nan)
# copy values to rows above
df1 = df1[['Suite','City/State']].backfill()
# joint the frames together on index
df = df.join(df1)
df.drop_duplicates(subset=['City/State'], keep='first', inplace=True)
# set the column order to what you want
df = df[['Comp ID', 'Type', 'Address', 'Suite', 'City/State', 'phone' ]]

输出

Comp ID Type Address Suite City/State phone
C1 W_sale 10 foo Suite A foo city 888-321-4567
C2 W_sale 11 spam STE 100 spam town 888-321-4567
C3 W_sale 12 ham Myhammy 888-321-4567

编辑:numpy where 语句:

numpy 由顶部的 import numpy as np 行引入。我们正在创建基于“Comp ID”列的计算列。 numpy 在没有循环的情况下执行此操作。将 where 想象成一个 excel IF() 函数。

df1(return value) = np.where(df[test] > condition, true, false)

【讨论】:

  • 我认为这可能有效。欣赏它!该文件有超过 10,000 行。手动创建字典是不可能的。这就是为什么我认为我可能需要创建一个循环。我应该如何更有效地创建字典?
  • 你不需要字典。在您的示例中,您没有提供让我重新制作数据的方法。所以这本字典是给我的,所以我可以提供你的示例数据的答案。您如何将数据加载到 pandas DataFrame 中?如果您不知道那么您的数据存储在哪里(.xlsx、.csv、html、SQL、parquet 等)?
  • 当你用数据提问时,你应该以字典的形式提供数据,它可以让人们更快地回答。
  • 我懂了。我的数据是一个 .xlsx 文件。
  • 明白你!市/州工作。但是套房里全是 NaN。你能解释一下这三行吗?我不明白他们。 df1['套房'] = np.where( df['Comp ID']=='', df['地址'], np.nan) df1['城市/州'] = np.where( df[' Comp ID'].isna(), df['Address'], np.nan) # 将值复制到上面的行 df1 = df1[['Suite','City/State']].backfill() 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
相关资源
最近更新 更多