我想根据 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/