python - 循环遍历占位符来创建 pandas 系列

标签 python pandas

我想根据 if 条件自动更改 pandas 列缺失值的名称,最好使用“string_name_number”。数字应从 1 开始,到最后一个缺失值结束。我决定按如下方式设置循环以从字符串中选择数据。

但是,缺失列的结果 (df2) 保持不变。如下; - 受访者我, jack 森,受访者我,受访者我,简,受访者我,玛丽,...

我期望看到以下结果(df2); - 受访者 1、 jack 森、受访者 2、受访者 3、简、受访者 4、玛丽、...

请帮忙。

import pandas as pd  

df = pd.read_csv('232 responses.csv', sep=',',header=0, parse_dates=True, 
                 index_col='Timestamp')

missing_rows_list = list(range(0, len (df)))

for i in missing_rows_list:
    i = 1
    df2 = [df['Name (optional)']\
           .replace(np.nan, 'respondent {d[i]}'\
           .format(d=missing_rows_list)) if pd.isnull(df['Name (optional)']) \
            else df['Name (optional)'] == word in df['Name (optional)']]
    i += 1

最佳答案

我认为这应该可以处理它,并且是一种更方便的方法:

df=pd.DataFrame({"a":["test1","test2","test3","test4",np.NAN],"b":["test5",np.NAN,"test7",np.NAN,"test9"]})

#Create the respondent + inex number format --> you can also save this in an extra df column if you like
a=["respondent"]*len(df.index)
b=list(df.index)
c=["{0}{1}".format(a_,b_)for a_,b_ in list(zip(a,b))]

#Replace the missing values
for i in df.columns:
    mask = df[i].isnull()
    df[i].mask(mask,c, inplace=True)

print(df)



           a          b
0      test1      test5
1      test2  response1
2      test3      test7
3      test4  response3
4  response4      test9

关于python - 循环遍历占位符来创建 pandas 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45395061/

相关文章:

python - 如何使用删除 NA 值的选项来融化 Pandas 中的数据框

python - 如何搜索其特定字段包含一个列表中的所有项目而不包含另一列表中的任何项目的文档?

python - 如何从不同的群体中获得相似的分布?

python - `.astype(' 分类') 和 `pd.Category(...)` 之间的 Pandas 差异

python - 如何将 Lambda 从 Octave 转换为 Python

python - 使用 numexpr 的欧几里德范数

python - pyspark 在分组的 applyInPandas 中添加多列(更改架构)

python - 计算 Pandas 中特定列和每一行的非零百分比

python - 如何向多索引 Pandas 数据帧添加新行和新列?

python - 为什么 DataFrame 列对于 json 转换必须是唯一的?