如果 .csv 文件中某一列下的一行包含 1,则应使用 python 覆盖另一列中的同一行,否则应留空
If a row under a column in a .csv file contains 1, then the same row in another column should be overwritten using python, else should be left empty
我有一个包含大约 300,000 行的 .csv 文件。我手动创建了一个新列,我希望从一些旧列中提取信息,但由于文件的长度,我无法手动执行此操作。旧列的标题是 Present、Online、Absent,新列的标题是 Attendance。
较旧的列的值为 1 和 0,其中观察结果为真或假,即如果事件出现观察结果,则 "Present" 列的值为 1,如果有其他值,则值为 0。与 "online" 和 "absent" 列相同。
我希望新列从旧列中获取信息,即如果任何旧列的值为 1,则 "Attendance" 中的同一行的值应为 "present"、"online" 或 "absent" 取决于哪个是正确的。
我一直在尝试使用 Pandas 来执行此操作,但还没有找到适用于 .csv 文件的方法。
for i in f['Present']:
if i == 1:
f['Attendance'].write("present")
我不介意该解决方案是否适用于一列并重复用于其他列。它不必一次对所有人起作用。
这是它应该的样子
谢谢
for i in range(len(df)):
if int(df.loc[i, 'present']) == 1:
df.loc[i, 'attend'] = 'present'
elif int(df.loc[i, 'online']) == 1:
df.loc[i, 'attend'] = 'online'
else:
df.loc[i, 'attend'] = 'absent'
您可以遍历dataframe的每一行,并根据前3列设置新列的值。
参考https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
更多 pandasonic 解决方案(比循环、条件列表和 loc),
实际上基于 Numpy 是:
df['Attendance'] = np.select([df.Present == 1, df.Online == 1, df.Absent == 1],
choicelist = ['present', 'online', 'absent'], default = '')
它应该 运行 比其他解决方案快得多。
有关详细信息,请参阅 np.select 的文档。
我有一个包含大约 300,000 行的 .csv 文件。我手动创建了一个新列,我希望从一些旧列中提取信息,但由于文件的长度,我无法手动执行此操作。旧列的标题是 Present、Online、Absent,新列的标题是 Attendance。 较旧的列的值为 1 和 0,其中观察结果为真或假,即如果事件出现观察结果,则 "Present" 列的值为 1,如果有其他值,则值为 0。与 "online" 和 "absent" 列相同。
我希望新列从旧列中获取信息,即如果任何旧列的值为 1,则 "Attendance" 中的同一行的值应为 "present"、"online" 或 "absent" 取决于哪个是正确的。 我一直在尝试使用 Pandas 来执行此操作,但还没有找到适用于 .csv 文件的方法。
for i in f['Present']:
if i == 1:
f['Attendance'].write("present")
我不介意该解决方案是否适用于一列并重复用于其他列。它不必一次对所有人起作用。
这是它应该的样子
谢谢
for i in range(len(df)):
if int(df.loc[i, 'present']) == 1:
df.loc[i, 'attend'] = 'present'
elif int(df.loc[i, 'online']) == 1:
df.loc[i, 'attend'] = 'online'
else:
df.loc[i, 'attend'] = 'absent'
您可以遍历dataframe的每一行,并根据前3列设置新列的值。
参考https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
更多 pandasonic 解决方案(比循环、条件列表和 loc), 实际上基于 Numpy 是:
df['Attendance'] = np.select([df.Present == 1, df.Online == 1, df.Absent == 1],
choicelist = ['present', 'online', 'absent'], default = '')
它应该 运行 比其他解决方案快得多。
有关详细信息,请参阅 np.select 的文档。