python - 用 Pandas 附加到数据框单元格?

标签 python pandas dataframe

我正在编写一个代码,根据某些列中的数据为人们分配标签。我正在使用 Pandas 数据框。我用一个初始值填充标签列没有问题,但如果一个人应该有多个标签,我无法弄清楚如何附加到初始值。

数据框将每个单元格视为一个字符串,很确定我希望它是一个列表。

df["Shopify Tags"] = ''
df.set_index(ID, inplace=True)

i = 0

for index, row in df.iterrows():

     if "Medical" in df.iloc[i,2]:

          df.iloc[i,4] = "#Medical"


     if "40" in df.iloc[i,2]:

         df.iloc[i,4].append('#Discount40')


 i+=1

我希望 Shopify 标签列最终在每一行中看起来像 #Medical, #Discount40, #OtherTags

这是我关于 SO 的第一个问题 :)

最佳答案

您的问题有两点值得注意:

  1. 在数据框中保存列表效率低下,不推荐使用。这是因为它们是通过指针存储的,而不是存储在连续的内存块中。这意味着无法进行矢量化计算。
  2. 您应该只在万不得已的情况下迭代数据框中的行。 Pandas 擅长向量化计算。即使对于非矢量化操作,也有一些方法可以避免显式 for 循环。

注意到这些要点后,下面是一种解决方案。

# example dataframe
df = pd.DataFrame({'col1': 1,
                   'col2': ['Medical 1234', 'Medical 40 Something',
                            '40 something', 'Nothing'],
                   'col3': 3})

# define function which creates a list from a dictionary mapping
def lister(x):
    mapping = {'Medical': '#Medical', '40': '#Discount40'}
    return [v for k, v in mapping.items() if k in x]

# apply function to series
df['col4'] = df['col2'].apply(lister)

print(df)

   col1                  col2  col3                     col4
0     1          Medical 1234     3               [#Medical]
1     1  Medical 40 Something     3  [#Medical, #Discount40]
2     1          40 something     3            [#Discount40]
3     1               Nothing     3        

关于python - 用 Pandas 附加到数据框单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50537266/

相关文章:

python tkinter treeview 右键单击​​(Button-3)事件以选择 TreeView 中的项目

python - 检查一个数据帧中的值是否存在于另一个数据帧中,打印所有值对

scala - Spark Dataframe 中 SQL 中的 Seq.contains

python - 映射 2 个数据帧并替换目标数据帧中匹配值的 header

python - 从 Excel 宏更新我的 wiki

python - 如何在 Pyramid notfound_view_config中返回HTTPMovedPermanently(301状态)而不是HTTPFound(302)

python - 在 Google Colab 上安装 LightGBM 的 GPU 支持

python - 在 Pandas 中读取文本文件时的左贪婪与右贪婪列分配

python - 如何在条件满足之前用 N 行中的某些行对条件行进行子集化,比我的代码更快?

R如何从一个数据帧划分到另一个数据帧对应的列名