我的CSV文件有一个问题,我需要循环遍历一个特定列中的所有字符串值,然后用其他东西替换它们。我已经在熊猫身上试过了,但是迭代制作了我的DataFrame的副本,并且更改没有保存。到目前为止,我尝试过的代码如下:
import pandas as pd
df = pd.read_csv("cexport-4.csv", encoding="iso-8859-1", sep=";", error_bad_lines=False)
psu = ["PSU 500W - 550W", "PSU 600W - 650W"]
for row in df["KATEGOORIA"]:
if row in psu:
row = "PSU"因此,我需要弄清楚的是,如何将列行值(如"PSU 500W -550 W“)重命名为"PSU”。
CSV文件如下(非常大的CSV文件的一部分):
,AK ID,TOODE,KATEGOORIA
0,330783.0,ASUS VGA PCIE16 GT730 2GB GDDR3/GT730-SL-2G-BRK-V2 ASUS,GeForce 700 Series
1,330694.0,"Chipolo Plus 2nd Generation Smart Tracker CH-CPM6-BK-R Black, Bluetooth tracker, iOS and Android phones with Bluetooth 4.0 connectivity or higher, Weight 9 g, ,Smartdevice accessories
2,330653.0,"Thermaltake Smart 500W RGB (80+ 230V EU, 2xPEG, 120mm, Single Rail) PSU",PSU 500W - 550W我尝试过导入CSV并这样做,但是我不知道如何访问一个列。真的很感激你的指导!
最好,Raidar
发布于 2018-11-10 16:48:10
创建字典和replace
psu = ["PSU 500W - 550W", "PSU 600W - 650W"]
d = dict.fromkeys(psu, 'PSU')
df["KATEGOORIA"] = df["KATEGOORIA"].replace(d)另一种方法是将map与fillna一起使用以获得更好的性能:
df["KATEGOORIA"] = df["KATEGOORIA"].map(d).fillna(df["KATEGOORIA"])另一种方法应该是用PSU替换以numpy.where开头的所有值。
mask = df["KATEGOORIA"].str.startswith('PSU')
#faster if no missing values
mask = [x.startswith('PSU') for x in df["KATEGOORIA"]]
df["KATEGOORIA"] = np.where(mask, 'PSU', df["KATEGOORIA"])https://stackoverflow.com/questions/53241153
复制相似问题