【问题标题】:Combine 2 columns based on the value of one of them in Python根据 Python 中其中一列的值组合 2 列
【发布时间】:2018-02-03 04:21:35
【问题描述】:

Education'] = df['Husband_Education'].astype(str) + df['Husband_Black']`我想将一列中的一些值与python中另一列的内容结合起来。该列的值为:“yes”、“No”和“Years”。我只想将所有“年份值迁移到另一列”我的数据如下所示:

我的数据:

+--------------------+---------------+
| Husband_education  | Husband black |
+--------------------+---------------+
| less than 12           years       |
+--------------------+---------------+
| 12 -15 years       | No            |
+--------------------+---------------+
| 12-15 years        | yes           |
+--------------------+---------------+

期望的输出:

+--------------------+---------------+
| Husband_education  | Husband black |
+--------------------+---------------+
| less than 12 years |     ---       |
+--------------------+---------------+
| 12 -15 years       | No            |
+--------------------+---------------+
| 12-15 years        | yes           |
+--------------------+---------------+

我希望所有等于“年”的单词移动到第一列,并在第二列中保留“是”和“否”的值,我有 3,772 行

我的代码看起来像这样有什么想法吗?

for row in df['Husband_Black']: if 'years' in row : df['Husband_Education'] = df['Husband_Education'].astype(str) + df['Husband_Black']

【问题讨论】:

  • 不清楚你想要完成什么。请提供预期结果的示例。
  • 提供预期的输出和你的努力,你尝试了什么,没有成功。
  • 我在代码前添加了输出,请查看我的帖子

标签: python dataframe


【解决方案1】:

我只想将所有“年份值迁移到另一列”我的数据看起来像这样我从中理解的是年份后面的值应该只迁移到另一列:有一个坏但易于提取年份值:

# read your data line by line.
data = open("yourdatafile","r")
counter = 1
column ={}
for line in data:
   year_record = []
   # split by year
   line= line.split('years')
   # your example becomes ['Husband_education Husband black less than 12 
   #', ' 12-15 ', ' No 12-15 ', ' yes']
   #  now record the value 
   temp = line[0]
   year_record.append(temp[-1])
   year_record.append([line[1])
   temp = line[2]
   year_record.append([temp[1])
   # Record this record_value to the respective column 
   column[counter] = year_record 
   counter =counter +1

【讨论】:

  • 我有一个 6 列的数据框,我想从第 3 列复制到第 2 列
  • 你能举个例子你到底想要什么吗?如果您只想从第 3 列复制到第 2 列,请使用 panda。将 pandas 导入为 pd,将您的问题放入数据框 pd.DataFrame 中。然后简单地复制 df['3rd'] = df['2nd'],其中 3rd 和 2nd 是您的列。
【解决方案2】:

问题解决了,我能够使用 np 并将整个数据帧放在一行中,而不是迭代:

    df['Husband_Education'] = np.where(df['Husband_Black']=='years',  df['Husband_Education'].map(str) + ' ' +'years', df['Husband_Education'])

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 2013-08-29
    • 2017-06-19
    相关资源
    最近更新 更多