python - 从 for 循环内部保存数据帧

标签 python pandas loops for-loop

我有一个函数,它接受一个数据帧并返回一个(简化的)数据帧,例如像这样:

def transforming_data(dataframe, col_1, col_2, normalized = True):
    ''' takes in dataframe, groups col_1 according to col_2 and returns dataframe
    '''
    df = dataframe[col_1].groupby(dataframe[col_2]).value_counts(normalize = normalized).unstack(fill_value = 0)

    return dataframe

对于以下代码,这给了我:

import pandas as pd
import numpy as np
np.random.seed(12)

def transforming_data(df, col_1, col_2, normalized = True):
    ''' takes in df, groups col_1 according to col_2 and returns df '''
    df = dataframe[col_1].groupby(dataframe[col_2]).value_counts(normalize = normalized).unstack(fill_value = 0)
    return df

numrows = 1000
dataframe = pd.DataFrame({'Numerical': np.random.randn(numrows), 
                         'Category': np.random.choice(['Panda', 'Elephant', 'Anaconda'], numrows),
                         'Response 1': np.random.choice(['Yes', 'Maybe', 'No', 'Don\'t know'], numrows),
                         'Response 2': np.random.choice(['Very Much', 'Much', 'A bit', 'Not at all'], numrows)})

test = transforming_data(dataframe, 'Response 1', 'Category')
print(test)
# Output
# Response 1  Don't know     Maybe        No       Yes
# Category                                            
# Anaconda      0.275229  0.232416  0.217125  0.275229
# Elephant      0.220588  0.270588  0.255882  0.252941
# Panda         0.258258  0.222222  0.273273  0.246246

到目前为止,一切顺利。

现在我想在 for 循环中为 dataframe 中的每一列使用函数 transforming_data (因为我有很多列,而不是只需两个)并将生成的数据帧保存到新的数据帧,例如本例中的 test_response_1test_response_2

有人能指出我正确的方向 - 即如何正确实现循环吗?

到目前为止,我正在使用类似的东西 - 但无法弄清楚如何保存数据框

for column in dataframe.columns.tolist():
    temp_df = transforming_data(dataframe, column, 'Category')
    # here, I need to save tmp_df outside of the loop but don't know how to

非常感谢您的指点和帮助。 (注意:most similar question I found 没有谈论实际保存数据帧,所以它对我没有帮助。

最佳答案

如果您想保存(在内存中)所有 temp_df是来自循环的,您可以将它们附加到一个列表中,然后可以对其进行索引:

temp_dfs = []
for column in dataframe.columns.tolist(): #you don't actually need the tolist() method here
    temp_df = transforming_data(dataframe, column, 'Category')
    temp_dfs.append(temp_df)

如果您希望能够访问这些temp_df是用于转换它们的列名,然后您可以将每个列分配给一个字典,使用列作为键:

temp_dfs = {}
for column in dataframe.columns.tolist():
    temp_df = transforming_data(dataframe, column, 'Category')
    temp_dfs[column] = temp_df

如果“保存”的意思是“写入磁盘”,那么您可以使用众多 to_<file_format>() 之一pandas提供的方法:

temp_dfs = {}
for column in dataframe.columns.tolist():
    temp_df = transforming_data(dataframe, column, 'Category')
    temp_df.to_csv('temp_df{}.csv'.format(column))

这是 to_csv() docs .

关于python - 从 for 循环内部保存数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56260926/

相关文章:

python-shell 在 emacs 中不工作

python - Pandas:使用不同的值填充组中相同索引的行

python - 值错误 : Unknown label type: 'unknown'

c++ - 在 C++ 中启动和停止线程内的循环

php - 使用购物车时我需要知道哪些变量?

python - 钻孔错误。在内建中找不到它

python正则表达式,拉出所有字母

python - Django mod-wsgi 一个类对象的多个实例

python - pandas read_csv() 输入本地日期时间字符串,tz_convert to UTC

Python 'For' 循环迭代数组