mirkice 2019-07-30 00:20 采纳率: 0%
浏览 1171

python pandas apply 原理求解,如何在dataframe 中将同一行的某个数值塞进df结构的一列?

有一个data frame结构,其中一列是data frame组成的,其他的列都是str或者数值之类的,如何将一行中str一类的塞入df里?

我试过apply,结果很诡异。。。
函数里print出来的结果是想要的,但是返回以后拿到的结果city就都是 tyu一个数值了

高手求解。。。

import pandas as pd


def testcc(df1):
    #tmpdf = df1
    tmpdf = df1['c']
    value = df1['a']
#    value = 111

    tmpdf['city']=value
    print(tmpdf)
    return tmpdf

df1 = pd.DataFrame({'a': ['qwe'],
                    'b': ['asd']})

df4 =df1

df3 = pd.DataFrame({'a': ['qwe']})

df2 = pd.DataFrame({'a': ['qwe', 'wer', 'ert', 'rty', 'tyu'],
                    'b': ['asd', 'sdf', 'dfg', 'fgh', 'ghj'],
                    'c': [df1,df3,df4,df1,df1]})

df2['d']=df2.apply(testcc,axis=1)

print('------------------')
print(df2['d'])

结果是

     a    b city
0  qwe  asd  qwe
     a    b city
0  qwe  asd  qwe
     a city
0  qwe  wer
     a    b city
0  qwe  asd  ert
     a    b city
0  qwe  asd  rty
     a    b city
0  qwe  asd  tyu
------------------
0         a    b city
0  qwe  asd  tyu
1                   a city
0  qwe  wer
2         a    b city
0  qwe  asd  tyu
3         a    b city
0  qwe  asd  tyu
4         a    b city
0  qwe  asd  tyu
Name: d, dtype: object
  • 写回答

2条回答 默认 最新

  • zqbnqsdsmd 2019-07-30 10:18
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?