【问题标题】:Iterating in dataframe and insert on text在数据框中迭代并插入文本
【发布时间】:2019-07-04 02:01:02
【问题描述】:

在 pandas 中加载了一个大小为 m*n 的 DataFrame,与列 n 相比,m 可以很大,值从 2 到 20。 m*n 中的每个值都必须添加到特定文本中,这意味着任何值之间的文本都是常量。

我尝试使用 ForIf 嵌套句子,没有很好的结果如何从 df.iloc[0,0] 到 df.iloc[m,n] 并插入文本。

textA + df.iloc[0,0] + textB + df.iloc[0,1] + .... + textX + df.iloc[0,n]
textA + df.iloc[1,0] + textB + df.iloc[1,1] + .... + textX + df.iloc[1,n]
.
.
.
textA + df.iloc[m,0] + textB + df.iloc[m,1] + .... + textX + df.iloc[m,n]

我有 2 个文件,一个包括 textA textB ... textX 第二个文件是生成 pandas 数据框的 csv 类型。

上面有数据框和文本准备数组。

感谢任何提示。

【问题讨论】:

  • 我不太明白你想要什么。您能否编辑您的问题并更清楚地写出您想要的结果?

标签: arrays python-3.x pandas


【解决方案1】:

您的要求并不完全清楚,但请查看以下代码是否能够帮助您在从文本文件添加信息时在 df.iloc[0,0] 到 df.iloc[m,n] 之间进行迭代(在本例为文本变量)

# i am using a dummy variable for the text data as i am not sure how your data look like
text = ['textA', 'textB', 'textC']
new_text = []

# using a nested for loop to iterate
for row in range(len(df)): 
    for col in range(len(df.columns)):
        new_text.append(text[col] + str(df.iloc[row, col]))

【讨论】:

  • text = ['textA', 'textB', 'textC'] 和 dataframe row1 2 4 6 的结果是textA2 textB4 textC6 和 dataframe row2 8 10 12 result textA8 textB10 textC12 等。文本是一行一行的常量,变量值为df.iloc [行,列]
  • 这是一个嵌套循环如何工作的示例,您可以尝试使其适应您的代码。我的示例中的文本为 ['textA', 'textB', 'textC'] 但在您的情况下,它可能只是另一个数据框或熊猫系列。根据您的要求,您声明您想要textA + df.iloc[0,0] + textB + df.iloc[0,1] + .... + textX + df.iloc[0,n],类似于“textA 2 textB 4 textC 6”,或者我是否缺少要求中的某些内容
猜你喜欢
  • 2018-11-17
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-15
  • 2021-03-20
相关资源
最近更新 更多