![](/img/trans.png)
[英]Pandas Dataframe Python | How to compare a cell with another cell of a copied dataframe?
[英]Python Pandas DataFrame cell changes disappear
我是python和pandas的新手,正在嘗試處理csv數據文件。 我加載兩個數據框,一個包含帶有關鍵字的列,另一個是帶有“ id”和“ word”列的“ bagOfWords”。 我想做的是在第一個數據幀中添加一列,其中關鍵字的ID位於“列表字符串”中,例如“ [1,2,8,99 ...]”。
到目前為止,這是我想出的
websitesAlchData = pd.io.parsers.read_csv('websitesAlchData.csv', sep=';', index_col='referer', encoding="utf-8")
bagOfWords = pd.io.parsers.read_csv('bagOfWords.csv', sep=';', header=0, names=["id","words","count"], encoding="utf-8")
a = set(bagOfWords['words'])
websitesAlchData['keywordIds'] = "[]"
for i in websitesAlchData.index
keywords = websitesAlchData.loc[i,'keywords']
try:
keywordsSet = set([ s.lower() for s in keywords.split(",") ])
except:
keywordsSet = set()
existingWords = a & keywordsSet
lista = []
for i in bagOfWords.index:
if bagOfWords.loc[i,'words'] in existingWords:
lista.append(bagOfWords.loc[i,'id'])
websitesAlchData.loc[i,'keywordIds'] = str(lista)
print(str(lista))
print(websitesAlchData.loc[i,'keywordIds'])
websitesAlchData.reset_index(inplace=True)
websitesAlchData.to_csv(path_or_buf = 'websitesAlchDataKeywordCode.csv', index=False, sep=";", encoding="utf-8")
for循環末尾的兩次打印給出了預期的結果,但是當我嘗試打印整個數據框“ websitesAlchData”時,“ keywordIds”列仍為“ []”,因此它也位於結果.csv中。
我的猜測是,我在某個地方創建了一個副本,但我無法確定在哪里。
任何想法在這里有什么問題,或者如何不同地做同一件事? 謝謝!
更新:
網站AlchData.cvs看起來像這樣
referer;category;keywords
url;int;word0,word2,word3
url;int;word1,word3
...
和cvc的話袋。
id;index;count
0;word0;11
1;word1;14
2;word2;14
3;word3;14
...
預期產量
referer;category;keywords;keywordIds
url;int;word0,word2,word3;[0,2,3]
url;int;word1,word3;[1,3]
將i
用於兩個for
循環肯定存在問題。 改變它,看看是否有幫助。
我會嘗試這樣的事情。 您需要分析較大數據集上的性能。
In [146]: df1
Out[146]:
referer category keywords
0 url int word0,word2,word3
1 url int word1,word3
[2 rows x 3 columns]
In [147]: df2
Out[147]:
id count
index
word0 0 11
word1 1 14
word2 2 14
word3 3 14
[4 rows x 2 columns]
將keywords
列拆分為單詞列表。 通常,將列表存儲在DataFrames中是一個糟糕的主意,但這是目前最直接的方法。
In [148]: vals = df1.keywords.str.split(',')
In [149]: vals
Out[149]:
0 [word0, word2, word3]
1 [word1, word3]
Name: keywords, dtype: object
然后從df2
到vals
中的列表的每個元素應用查找:
In [151]: ids = vals.apply(lambda x: [df2.loc[y, 'id'] for y in x])
In [152]: ids
Out[152]:
0 [0, 2, 3]
1 [1, 3]
Name: keywords, dtype: object
最后連拍:
In [154]: df = pd.concat([df1, ids], axis=1)
In [155]: df
Out[155]:
referer category keywords keywords
0 url int word0,word2,word3 [0, 2, 3]
1 url int word1,word3 [1, 3]
[2 rows x 4 columns]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.