循环通过占位符来创建一个熊猫系列

时间:2017-07-29 23:44:27

标签: python pandas

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

然而,缺失列的结果(df2)保持不变。如下; - 受访者我,jakson,受访者我,受访者我,简,受访者我,玛丽,......

我希望看到以下结果(df2); - 受访者1,jakson,受访者2,受访者3,jane,受访者4,mary,......

请协助。

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

1 个答案:

答案 0 :(得分:2)

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

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