python - 如何访问串行存储的单个元组值?
问题描述
我有一个数据框,每个单元格中都包含一个元组。
import pandas as pd
inp = [[(11,110), (12,120)],
[(13,130), (14,140), (15,150)]]
df = pd.DataFrame(inp)
for index, row in df.iterrows():
print(row)
我希望以行迭代方式访问每个元素。如您所见, iterrows() 以行方式返回一系列元组,而不是它的单个值。例如,它给了我 (11, 110) ... (15, 150)。我想把它们分成一个整数。
期望的结果应该让我通过索引以行方式访问元组的单个值。例如,在行迭代中,我能够从 index[0] 获得 11、12、13、14、15,而从 index[1] 获得 110、120、130、140、150
在 iterrows() 中可以这样做吗?
预先感谢!
解决方案
首先,只能DataFrame.iterrows()
作为最后的手段使用。DataFrames 针对整个列的向量化操作进行了优化,而不是针对逐行操作。如果您必须迭代,请考虑使用,DataFrame.itertuples()
因为它保留了每列的数据类型并且运行速度更快。
其次,在 Pandas(以及所有计算,真的)中,为手头的任务适当地构建数据是很重要的。您当前的解决方案将索引和时间点的人员作为列。正如您的示例所示,这会产生一个宽阔、参差不齐的矩阵,其中可能包含许多 NaN。听起来您想为 DataFrame 的每个单元格存储四个数据元素:人、时间、x 和 y。考虑在每个时间点使用四列而不是一列,如下所示:
import pandas as pd
inp = [[(11,110), (12,120)],
[(13,130), (14,140), (15,150)]]
df = pd.DataFrame(inp) # ragged and wide--not ideal for Pandas
df2 = df.stack() # now each element is indexed by a MultiIndex (person and time).
df2.index.rename(["person", "time"], inplace=True) # to be explicit
df3 = pd.DataFrame(df2.tolist(), index=df2.index) # now each row is a person/time and there are two columns for x and y
df3.reset_index(inplace=True) # not strictly necessary
df3.rename(columns={0: "x", 1: "y"}, inplace=True) # to be explicit
for row in df3.itertuples(): # using itertuples instead of iterrows
print(row)
# Pandas(Index=0, person=0, time=0, x=11, y=110)
# Pandas(Index=1, person=0, time=1, x=12, y=120)
# Pandas(Index=2, person=1, time=0, x=13, y=130)
# Pandas(Index=3, person=1, time=1, x=14, y=140)
# Pandas(Index=4, person=1, time=2, x=15, y=150)
你应该看看这个答案,了解我是如何拆分元组的。当然,如果您有能力控制数据的构建方式,则无需进行此类操作——只需首先创建具有适当结构的 DataFrame。
现在,您可以将df3["x"]
和df3["y"]
视为pandas.Series
您需要做的任何事情的对象:
for x in df3["x"]:
print(x)
# 11
# 12
# 13
# 14
# 15
for y in df3["y"]:
print(y)
# 110
# 120
# 130
# 140
# 150
print(df3["x"] * df3["y"]/5 + 1)
# 0 243.0
# 1 289.0
# 2 339.0
# 3 393.0
# 4 451.0
# dtype: float64
推荐阅读
- php - 如何在 cakephp 中正确构建这个 mysql 连接查询?
- javascript - 在 JavaScript If..Else 语句中使用逻辑运算符“&&”时得到“未定义”结果
- php - 将数组重组为关联数组
- node.js - 将多个变量传递给 package.json 脚本
- javascript - 如何自动幻灯片放映
- java - JVM 和 C++ 之间的纳秒精度差异
- javascript - 我正在尝试使用 jQuery 操作页面上的特定链接
- c# - 简明的键值对动态列表
- laravel - Spatie 媒体库 - 覆盖后删除原件
- python - 错误地在双“for”循环内建立索引