我是 python 的新手。我正在处理包含以下内容的 csv 文件
Name, Description, Price
Comp1, comp desc, 60
Comp1, comp desc, 100
Comp1, comp desc, 250
Comp1, comp desc, 90
Comp1, comp desc, 125
Comp1, comp desc, 600
Comp1, comp desc, 395
...
我正在尝试读取文件,如果有任何重复项(基于名称),请将其删除。然后如果价格 < 50 删除那些。然后添加一个名为“质量”的新列。然后,如果价格 < 80,则将“该行的质量”设置为“平均”,如果价格 < 125,则将价格设置为“高”。
我正在尝试为此使用 Pandas(我尝试使用 csv 模块,但 3 天后无法弄清楚...)
到目前为止,我可以添加一个新列。我不确定如何删除满足条件的行(令人惊讶的是,我在帖子中找不到符合我条件的内容)
我尝试了以下操作,但我收到一条错误消息“系列的真值不明确...
代码:
#python 3.6
import pandas as pd
csv_input = pd.read_csv("d:\python programs\chairs.csv")
csv_input["Quality"] = ""
csv_input.loc[csv_input["Price"] > 50 and csv_input["Price"] < 125, "Quality"] = "Average"
csv_input.loc[csv_input["Price"] > 125, "Quality" = "High"]
csv_input.to_csv("d:\python programs\output2.csv", index=False)
print (csv_input.iloc[:, 2])
最后一行只是检查我是否正在使用任何帮助表示感谢。
谢谢
更新: 我能够更新代码以使其执行一些我想要的操作,但是我仍然需要了解如何删除价格 >= 50 的行(示例)。
这是更新后的代码:
import pandas as pd
csv_input = pd.read_csv("d:\python programs\chairs.csv")
csv_input["Quality"] = ""
'This line set the Quality to average if the value is ,= 125'
csv_input.loc[csv_input["Price"] <= 125, "Quality"] = "Average"
'This line sets the Quality to high if the Price is above 125'
csv_input.loc[csv_input["Price"] > 125, "Quality"] = "High"
'This line writes to an output file'
csv_input.to_csv("d:\python programs\output2.csv", index=False)
print (csv_input.iloc[:, 2])
再次感谢所有评论和帮助。我很感激。
请您参考如下方法:
使用 &运算符而不是 and在索引中,如果条件由一些逻辑运算符分隔,也将条件括在括号中:
import pandas as pd
csv_input = pd.read_csv("d:\python programs\chairs.csv")
csv_input["Quality"] = ""
csv_input.loc[(csv_input["Price"] > 50) & (csv_input["Price"] < 125), "Quality"] = "Average"
# in the next string '[' just moved to the right place
csv_input.loc[csv_input["Price"] > 125, "Quality"] = "High"
csv_input
Out:
Name Description Price Quality
0 Comp1 comp desc 60 Average
1 Comp1 comp desc 100 Average
2 Comp1 comp desc 250 High
3 Comp1 comp desc 90 Average
4 Comp1 comp desc 125
5 Comp1 comp desc 600 High
6 Comp1 comp desc 395 High
解释: csv_input["Price"] < 125返回以下具有 bool 值的 pd.Series:
0 True
1 True
2 False
3 True
4 False
5 False
6 False
在 python 中,and kwd 不能重载,但是 &或其他(按位)逻辑运算符运算符即可。 所以,(csv_input["Price"] > 50) & (csv_input["Price"] < 125)再次返回 pd.Series(有关索引的更多信息):
0 True
1 True
2 False
3 True
4 False
5 False
6 False
该系列将用作 .loc[] 的 bool 掩码. (看起来和前一个系列一样,因为 (csv_input["Price"] > 50) 都是 True )
如果你想删除重复的行,试试 pd.DataFrame.drop_duplicates().
