gpt4 book ai didi

python - 替换现有列 .csv pandas 中的值

转载 作者:行者123 更新时间:2023-11-30 22:04:29 35 4
gpt4 key购买 nike

假设我有一个 csv,其中示例行如下所示: [' ', 1, 2, 3, 4, 5] 其中 表示空单元格。我想迭代 .csv 中的所有行,并将每行第一列中的所有值替换为另一个值,即 [100, 1, 2, 3, 4, 5]。这怎么可能做到呢?还值得注意的是,这些列没有标签(它们是从 .xlsx 转换而来的)。

目前,我正在尝试这样做:

for i, row in test.iterrows():
value = randomFunc(x, row)

test.loc[test.index[i], 0] = value

但这会在末尾添加一个带有标签 0 的列。

最佳答案

使用iloc用于按位置选择第一列 replace通过正则表达式来表示零个或多个空格:

df = pd.DataFrame({
0:['',20,' '],
1:[20,10,20]
})


df.iloc[:, 0] = df.iloc[:, 0].replace('^\s*$',100, regex=True)
print (df)
0 1
0 100 20
1 20 10
2 100 20

关于python - 替换现有列 .csv pandas 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53274696/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com