我有一个csv文件,我正在打开熊猫。 其中一列名为“standardUpc”,包含以下格式的数据:
['45783425568']
我想删除两个字符串:"['"
和"']"
,以便standardUpc列只有以下值:
45783425568
这是我的密码:
fileloc = "C:/Users/products.csv"
products = pd.read_csv(fileloc)
# COLUMN NAMES ARE: ['productId','title','standardUpc','sellerName','canAddToCart']
# This line only selects conditions where canAddToCart evaluates to True
filtered = (products[(products['canAddToCart'] == True) ])
# Replace the [' and the '] characters in the standardUpc column
filtered["standardUpc"] = filtered["standardUpc"].str.replace("['","")
filtered["standardUpc"] = filtered["standardUpc"].str.replace("']","")
#Now filter further on seller name
filtered_2 =(filtered[(filtered['sellerName'] == 'Robert')])
#print the new dataframe
for index, row in filtered_2.iterrows():
print (row["productId"], row["sellerName"],row["standardUpc"])
#export the filtered dataframe containing the modified UPC string to a new csv file
filtered_2.to_csv('instock.csv')
这将在此行生成错误:sre_constants.error: unterminated character set at position 0
:
filtered["standardUpc"] = filtered["standardUpc"].str.replace("['","")
总结:
我想将CSV文件读入数据帧结构,修改该结构中特定列中的值 dataframe,过滤dataframe中的特定条件,然后将所有这些内容写入新的csv文件
我不想处理数据帧的“视图”。实际上,我正在更改值并将其写入新的CSV文件
Pandas对
str.replace
方法使用正则表达式这就是您在此行中得到错误
sre_constants.error: unterminated character set at position 0
的原因对包含正则表达式中具有特殊含义的字符的字符串使用
re.escape
:相关问题 更多 >
编程相关推荐