我有一只DataFrame熊猫:
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print df
Run Code Online (Sandbox Code Playgroud)
输出:
c1 c2
0 10 100
1 11 110
2 12 120
Run Code Online (Sandbox Code Playgroud)
现在我想迭代这个帧的行.对于每一行,我希望能够通过列的名称访问其元素(单元格中的值).例如:
for row in df.rows:
print row['c1'], row['c2']
Run Code Online (Sandbox Code Playgroud)
是否有可能在熊猫中做到这一点?
我发现了类似的问题.但它没有给我我需要的答案.例如,建议使用:
for date, row in df.T.iteritems():
Run Code Online (Sandbox Code Playgroud)
要么
for row in df.iterrows():
Run Code Online (Sandbox Code Playgroud)
但我不明白row对象是什么以及如何使用它.
最近开始从我的安全地点(R)扩展到Python,并且对于细胞定位/选择感到有些困惑Pandas.我已经阅读了文档,但我很难理解各种本地化/选择选项的实际意义.
.loc或.iloc超过最常用的选项.ix吗?.loc,iloc,at,和iat可以提供一些保证正确性是.ix不能提供的,但我也看到了在那里.ix往往是一刀切最快的解决方案..ix?我正在进行一些地理编码工作,我曾经用selenium屏幕抓取我需要的位置地址的xy坐标,我将xls文件导入到panda数据帧,并希望使用显式循环来更新没有xy坐标的行,如下面:
for index, row in rche_df.iterrows():
if isinstance(row.wgs1984_latitude, float):
row = row.copy()
target = row.address_chi
dict_temp = geocoding(target)
row.wgs1984_latitude = dict_temp['lat']
row.wgs1984_longitude = dict_temp['long']
Run Code Online (Sandbox Code Playgroud)
我已经读过为什么在我对一个pandas DataFrame进行操作后,这个函数"没有"?并且我完全清楚iterrow只给了我们一个视图而不是一个副本进行编辑,但如果我真的要逐行更新值呢?是否lambda可行?
我一直在探索如何优化我的代码并运行pandas .at方法.根据文档
基于标签的快速标量访问器
与loc类似,at提供基于标签的标量查找.您也可以使用这些索引器进行设置.
所以我跑了一些样品:
import pandas as pd
import numpy as np
from string import letters, lowercase, uppercase
lt = list(letters)
lc = list(lowercase)
uc = list(uppercase)
def gdf(rows, cols, seed=None):
"""rows and cols are what you'd pass
to pd.MultiIndex.from_product()"""
gmi = pd.MultiIndex.from_product
df = pd.DataFrame(index=gmi(rows), columns=gmi(cols))
np.random.seed(seed)
df.iloc[:, :] = np.random.rand(*df.shape)
return df
seed = [3, 1415]
df = gdf([lc, uc], [lc, uc], seed)
print df.head().T.head().T
Run Code Online (Sandbox Code Playgroud)
df 好像:
a
A B C D E …Run Code Online (Sandbox Code Playgroud) 使用Pandas中的漂亮索引方法,我可以通过各种方式提取数据.另一方面,我仍然对如何更改现有DataFrame中的数据感到困惑.
在下面的代码中,我有两个DataFrame,我的目标是从第二个df的值更新第一个df中特定行的值.我怎样才能做到这一点?
import pandas as pd
df = pd.DataFrame({'filename' : ['test0.dat', 'test2.dat'],
'm': [12, 13], 'n' : [None, None]})
df2 = pd.DataFrame({'filename' : 'test2.dat', 'n':16}, index=[0])
# this overwrites the first row but we want to update the second
# df.update(df2)
# this does not update anything
df.loc[df.filename == 'test2.dat'].update(df2)
print(df)
Run Code Online (Sandbox Code Playgroud)
给
filename m n
0 test0.dat 12 None
1 test2.dat 13 None
[2 rows x 3 columns]
Run Code Online (Sandbox Code Playgroud)
但我怎样才能做到这一点:
filename m n
0 test0.dat 12 None
1 test2.dat 13 16 …Run Code Online (Sandbox Code Playgroud) 假设我有一个数据框,如下所示:
d = {'option1': ['1', '0', '1', '1'], 'option2': ['0', '0', '1', '0'], 'option3': ['1', '1', '0', '0'], 'views': ['6', '10', '5', '2']
df = pd.DataFrame(data=d)
print(df)
option1 option2 option3 views
0 1 0 1 6
1 0 0 1 10
2 1 1 0 5
3 1 0 0 2
Run Code Online (Sandbox Code Playgroud)
我正在尝试构建一个 for 循环,迭代每一列(“视图”列除外)和每一行。如果单元格的值不为 0,我想将其替换为同一行中“views”列的相应值。
需要以下输出(应该更容易理解):
option1 option2 option3 views
0 6 0 6 6
1 0 0 10 10
2 5 5 0 5
3 2 0 0 2 …Run Code Online (Sandbox Code Playgroud) 是)我有的:
我想做的事:
我已经有以下代码,它可以正常工作.但是,分析表明此代码是我的代码中的重要瓶颈之一,所以我想尽可能优化它,我也有理由相信应该是可能的:
df["NewColumn1"] = df.apply(lambda row: compute_new_column1_value(row), axis=1)
df["NewColumn2"] = df.apply(lambda row: compute_new_column2_value(row), axis=1)
# a few more lines of code like the above
Run Code Online (Sandbox Code Playgroud)
我基于这个答案解决这样的问题这一个(这是与我相似,但具体如何添加一个新列的问题,而我的问题是关于添加了许多新的列).我想这些df.apply()调用中的每一个都是通过所有行的循环在内部实现的,我怀疑应该可以使用只循环所有循环一次的解决方案来优化它(而不是每列需要添加一次) ).
在其他答案中,我看到了对assign()函数的引用,它确实支持一次添加多个列.我尝试以下列方式使用它:
# WARNING: this does NOT work
df = df.assign(
NewColumn1=lambda row: compute_new_column1_value(row),
NewColumn2=lambda row: compute_new_column2_value(row),
# more lines like the two above
)
Run Code Online (Sandbox Code Playgroud)
这不起作用的原因是因为lambda实际上根本没有接收到数据帧的行,它们似乎只是立刻得到整个数据帧.然后期望每个lambda一次返回完整的列/ Series /数组值.所以,我的问题是,我必须最终在这些lambda中通过所有循环实现手动循环,这显然会对性能更糟.
我可以从概念上考虑两种解决方案,但到目前为止还无法找到如何实际实现它们:
类似的东西df.assign()(支持一次添加多个列),但能够将行传递到lambda而不是完整的数据帧
一种向我的compute_new_columnX_value()函数进行向量化的方法,以便它们可以像df.assign()预期的那样用作lambda .
到目前为止我的第二个解决方案的问题是基于行的版本我的一些函数看起来如下,我很难找到如何正确地向量化它们:
def compute_new_column1_value(row):
if row["SomeExistingColumn"] …Run Code Online (Sandbox Code Playgroud) 任何人都可以建议一种方式回答相同的问题(请参阅链接),但通过使用lambda函数: 在逐行迭代时更新pandas中的数据帧