簡體   English   中英

Python Pandas:如何從另一個csv文件更新一個csv文件

[英]Python Pandas: how to update a csv file from another csv file

我們有兩個CSV文件: a.csvb.csv

a.csv具有樹列: labelitem1item2 b.csv有兩列: item1item2 ITEM1ITEM2 a.csv也occurr在b.csv ,這是a.csvb.csv具有相同的物品1項目2,標簽中的值a.csv應為1來代替。 如何用大熊貓來應對?


例如:

a.csv:

label    item1     item2
 0         123       35
 0         342       721
 0         876       243

b.csv:

item1     item2
 12        35
 32        721
 876       243

result.csv:

label    item1     item2
 0         123       35
 0         342       721
 1         876       243

我試過了,但是不起作用:

import pandas as pd

df1 = pd.read_csv("~/train_dataset.csv", names=['label', 'user_id', 'item_id', 'behavior_type', 'user_geohash', 'item_category', 'time','sales'], parse_dates=True)
df2 = pd.read_csv(~/train_user.csv", names=['user_id', 'item_id', 'behavior_type', 'user_geohash', 'item_category', 'time', 'sales'], parse_dates=True)
df1.loc[(df1['user_id'] == df2['user_id'])& (df1['item_id'] == df2['item_id']), 'label'] = 1

您可以使用loc和布爾條件屏蔽df(此處表示a.csv),如果滿足該條件,則將標簽設置為1:

In [18]:

df.loc[(df['item1'] == df1['item1'])& (df['item2'] == df1['item2']), 'label'] = 1
df
Out[18]:
   label  item1  item2
0      0    123     35
1      0    342    721
2      1    876    243

如果要設置所有行值,則可以使用np.where

In [19]:

np.where((df['item1'] == df1['item1'])& (df['item2'] == df1['item2']), 1, 0)
Out[19]:
array([0, 0, 1])
In [20]:

df['label'] = np.where((df['item1'] == df1['item1'])& (df['item2'] == df1['item2']), 1, 0)
df
Out[20]:
   label  item1  item2
0      0    123     35
1      0    342    721
2      1    876    243

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM