将新的 dataFrame 列添加到 pandas 中的同一数据框

Adding new dataFrame column to the same dataframe in pandas

问题:收到 SettingWithCopy 警告。

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

目标: 将列数据分成单独的列,全部在同一个 DataFrame 中。

输入: 具有 2 列的数据框。第一列是电子邮件地址,第二列包含以分号分隔的日期列表。

代码:

for dt in lunch_dates:
    roulette_data[dt] = roulette_data['date'].str.contains(dt).map(bool_conversion)

我想让这段代码做什么(它确实做了): 为原始日期列中找到的每个日期 (dt) 添加一个新列。

问题:在这种情况下如何使用 iloc,以确保我没有在内存中处理数据帧的可能副本?

你的例子

没有数据来测试它,我无法测试它,但下面应该可以工作(用电子邮件列的名称替换你的 'email_column_name'):

dates = pd.get_dummies(
                       roulette_data.set_index('email_column_name')['date']\
                       .str.split(';',expand=True)\
                       .stack().reset_index(level=1, drop=True)
                      )\
                      .reset_index().groupby('email_column_name').sum()

这是一个玩具示例:

df = pd.DataFrame({'col1':['record1', 'record2'], 
                  'col2':["this is good text", "but this is even better"]}
                 )

df
#      col1                     col2
#0  record1        this is good text
#1  record2  but this is even better

我们首先设置索引为col1,然后我们selectcol2,这样我们就可以使用它的.str.split方法将行拆分成单个单词。

df.set_index('col1')['col2'].str.split(expand=True)
#            0     1     2     3       4
#col1                                   
#record1  this    is  good  text    None
#record2   but  this    is  even  better

然后我们使用stack改变形状和reset_index去掉不必要的索引层

df.set_index('col1')['col2'].str.split(expand=True)\
            .stack().reset_index(level=1, drop=True) 
#col1
#record1      this
#record1        is
#record1      good
#record1      text
#record2       but
#record2      this
#record2        is
#record2      even
#record2    better
#dtype: object

我们将整个表达式包装在 pd.get_dummies()

pd.get_dummies(df.set_index('col1')['col2'].str.split(expand=True).stack().reset_index(level=1, drop=True))

#         better  but  even  good  is  text  this
#col1                                            
#record1       0    0     0     0   0     0     1
#record1       0    0     0     0   1     0     0
#record1       0    0     0     1   0     0     0
#record1       0    0     0     0   0     1     0
#record2       0    1     0     0   0     0     0
#record2       0    0     0     0   0     0     1
#record2       0    0     0     0   1     0     0
#record2       0    0     1     0   0     0     0
#record2       1    0     0     0   0     0     0

最终结果

最后我们 reset_index(即 col1 或者在您的情况下是电子邮件列),groupby col1 并对其求和。

pd.get_dummies(
               df.set_index('col1')['col2']\
               .str.split(expand=True)\
               .stack().reset_index(level=1, drop=True)
              )\
              .reset_index().groupby('col1').sum()
#         better  but  even  good  is  text  this
#col1                                            
#record1       0    0     0     1   1     1     1
#record2       1    1     1     0   1     0     1