从值列表添加或更新熊猫数据框

时间:2019-09-17 08:17:02

标签: python pandas

我有一个数据框

>>> df
  name  count
0    a      1
1    b      2
2    c      0

我想使用此列表更新值

 l = ['a','b','d']

所以我更新的df应该看起来像这样

>>> df
  name  count
0    a      2
1    b      3
2    c      0
3    d      1

我能想到的唯一方法是使用循环。你们可以提出其他建议吗? 谢谢

3 个答案:

答案 0 :(得分:3)

您可以从列表创建Series并按Series.value_counts获取计数,然后通过DataFrame.set_indexSeries.addSeries创建df,最后DataFrame使用Series.rename_axis  和Series.reset_index

l = ['a','b','d']

add = pd.Series(l).value_counts()
print (add)
d    1
a    1
b    1
dtype: int64

df1 = (df.set_index('name')['count']
         .add(add, fill_value=0)
         .astype(int)
         .rename_axis('name')
         .reset_index(name='count'))
print (df1)
  name  count
0    a      2
1    b      3
2    c      0
3    d      1

答案 1 :(得分:1)

另一种方法是将值彼此和GroupBy.count相加:

x = sorted(list(set(df['name'].tolist() + l)))
new = pd.concat([df['name'].repeat(df['count']).to_frame()
                 , pd.DataFrame({'name':l})]).groupby('name')['name'].count()
new = new.reindex(x, fill_value=0).reset_index(name='count')

输出

print(new)
  name  count
0    a      2
1    b      3
2    c      0
3    d      1

答案 2 :(得分:0)

我认为在这些情况下使用计数器是合适的。 唯一的缺点是从df转换为dict,反之亦然。

from collections import Counter

# initialize your variables
df = pd.DataFrame({'name': ['a', 'b', 'c'],
                   'count': [1, 2, 0]})
l = ['a', 'b', 'd']

# convert to dict with name - count pairs and update with counter of l
df_as_dict = dict(zip(df['name'].values, df['count'].values))
df_as_dict.update(Counter(df_as_dict) + Counter(l))

# create dataframe with updates values
new_df = pd.DataFrame({'name': list(df_as_dict.keys()), 
                       'count': list(df_as_dict.values())})
# ensure df format
new_df = new_df.sort_values('name').reset_index(drop=True)

new_df

输出

   count name
0      2    a
1      3    b
2      0    c
3      1    d