python - 如何在 pandas 数据框中重复迭代?
问题描述
对 Python 来说非常新,我有一个大数据框,每次用户输入 =“yes”时,我都尝试显示 5 行原始数据。
我已经尝试过使用 .iloc 和 .iterrows,但我不知道如何让输出超出我在 iloc 中定义的行。
这是我到目前为止所尝试的。
def raw_data(df):
"""
Asks user if they want to see 5 lines of raw data.
Then returns 5 lines of raw data if user inputs `yes`. Iterates until user response with a `no`
"""
data = df
while True:
answer = input('Would you like to see 5 lines of raw data? Enter yes or no: ')
if answer.lower() == 'yes':
print(data.iloc[:5])
data += 5
else:
break
我试图使用data += 5
进度,但它触发“ValueError:无法在没有频率的情况下将整数值添加到时间戳。”
我很困惑下一步该往哪个方向走。非常感谢帮助,
解决方案
DataFrame.iloc
将行索引作为第一个索引,将要显示的列索引作为第二个索引。
因此,如果您只想显示一大块 5 行并且所有列都使用:
df.iloc[idx:idx+5, :]
完整示例:
def raw_data(df):
"""
Asks user if they want to see 5 lines of raw data.
Then returns 5 lines of raw data if user inputs `yes`. Iterates until user response with a `no`
"""
idx = 0
while True:
answer = input('Would you like to see 5 lines of raw data? Enter yes or no: ')
if answer.lower() == 'yes':
print(df.iloc[idx:idx+5, :])
idx += 5
else:
break
另请参阅https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html
推荐阅读
- html - 将 Anchor CMS 博客部分添加到现有的 html/bootstrap 网站
- xml - XSLT 在生成后崩溃。所有属性都是不可见的
- angular - 由模块的 @NgModule 装饰器中的 APP_INITIALIZER 填充的 Angular 使用服务
- sql - 获取不同语言的不同代码客户端
- java - 如何通过 Pentaho 8 CE 中用户定义的 java 表达式将日期格式更改为 yyyy.mm.dd?
- r - 从受密码保护的网站下载 CSV
- ruby-on-rails - 在 ROR Heroku 中更改模式表后的部署问题
- reactjs - 空的在 ReactJs 中使用异步路由器时添加
- powershell - 使用变量在远程计算机上设置执行策略
- protocol-buffers - 自定义 FileInputFormat 始终将一个文件拆分分配给一个插槽