【问题标题】:pandas dataframe loc usage: what does supplying length of index to loc actually mean?pandas dataframe loc 用法:向 loc 提供索引长度实际上是什么意思?
【发布时间】:2022-06-11 01:22:22
【问题描述】:
我已阅读有关数据框 loc 的信息。我不明白为什么dataframe(indexPD) 的长度作为第一个参数提供给loc。这个loc基本上是什么意思?
tp_DataFrame = pd.DataFrame(columns=list(props_file_data["PART_HEADER"].split("|")))
indexPD = len(tp_DataFrame)
tp_DataFrame.loc[indexPD, 'item_id'] = something
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
这只是告诉 pandas 你想对数据框该列的所有行进行操作。考虑这个熊猫数据框:
df = pd.DataFrame(zip([1,2,3], [4,5,6]), columns=['a', 'b'])
a b
0 1 4
1 2 5
2 3 6
您的转换df.loc[len(df), 'b'] = -1 等效于df.loc[:, 'b'] = -1。您正在将此-1 转换应用于所需列的所有行,两者都产生:
a b
0 1 -1
1 2 -1
2 3 -1
第一个参数的目的是让您指定该列中的哪些索引将遭受转换。例如,如果您只希望前 2 行发生转换,那么您可以这样指定:
df.loc[[0,1], 'b'] = -1
a b
0 1 -1
1 2 -1
2 3 6