在以下结构的 pandas Dataframe 中:
mcve_data =
alfa alfa_id beta beta_id
a,c 7 c,de 8
c,d 7 d,f 9
l,mnk 8 c,d 9
j,k 8 d,e 9
tk,l 8 n,k 11
- 我想在每行中运行一个 for 循环,读取
key
(alfa 和 beta)和key_index
(alfa_index、beta_index)中的值。 - 如果
键
中的值的长度超过3
或者任何值的长度超过1个字符。我希望将key-values
和key-index
都转换为句点.
。
最终预期输出:
alfa alfa_id beta beta_id
a,c 7 . .
c,d 7 d,f 9
. . c,d 9
j,k 8 d,e 9
. . n,k 11
我想编写一个类似的函数(但它没有正常工作):
def check_and_convert(mcve_data):
labels = (l, l + id) for l in mcve_data.columns.values
def convert(lines):
for l,id in labels:
if len(l) > 3:
l = '.'
id = '.'
return l, id
write this back to the file.
任何建议,
最佳答案
您还可以使用 str
访问器一次性检查列中每个值的长度,从而跳过内部 for 循环:
keys = [k for k in df.columns if not k.endswith('_id')]
for k in keys:
df.loc[df[k].str.len()>3,[k,k+'_id']] = '.'
关于python - 如何根据列的值更新列值及其相应的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058100/